2010-08-16 64 views

回答

9

使用的TypeIsInterface属性..

public void DoCoolStuff<T>() 
{ 
    if(typeof(T).IsInterface) 
    { 
     //TODO: Cool stuff... 
    } 
} 
+0

就像在桶里拍摄鱼一样! – 2010-08-16 03:46:38

4

您可以显式检查使用typeof运营商和Type.IsInterface财产泛型类型参数。

void MyMethod<T>() { 
    bool isInterface = typeof(T).IsInterface; 
} 
5

如果你想约束您的通用方法,以便类型参数只能实现一些特定接口并没有什么意外的话,你应该做以下类型:

void YourGenericMethod<T>() where T : IYourInterface { 
    // Do stuff. T is IYourInterface. 
} 
+0

+1我没有想过,但这可能是OP试图解决的实际问题。 – 2010-08-16 03:57:23

+0

这是最佳做法 – 2010-08-16 03:58:18

相关问题