I have a generic function and I want to check whether the type parameter is an interface. Is there anyway to do that? Thanks in advance!
Use the IsInterface
property of Type
..
public void DoCoolStuff<T>()
{
if(typeof(T).IsInterface)
{
//TODO: Cool stuff...
}
}
If you want to constrain your generic method so that the type parameter can only be a type that implements some specific interface and nothing else, then you should do the following:
void YourGenericMethod<T>() where T : IYourInterface {
// Do stuff. T is IYourInterface.
}
You can explicitly check the generic type parameter using typeof
operator and Type.IsInterface
property.
void MyMethod<T>() {
bool isInterface = typeof(T).IsInterface;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.