2010-03-26 110 views
6

如何获取实例的通用接口类型?C#如何检查一个类是否实现泛型接口?

假设验证码:

interface IMyInterface<T> 
{ 
    T MyProperty { get; set; } 
} 
class MyClass : IMyInterface<int> 
{ 
    #region IMyInterface<T> Members 
    public int MyProperty 
    { 
     get; 
     set; 
    } 
    #endregion 
} 


MyClass myClass = new MyClass(); 

/* returns the interface */ 
Type[] myinterfaces = myClass.GetType().GetInterfaces(); 

/* returns null */ 
Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface<int>).FullName); 

回答

5

为了得到你需要使用名称属性,而不是在全名属性的通用接口:

MyClass myClass = new MyClass(); 
Type myinterface = myClass.GetType() 
          .GetInterface(typeof(IMyInterface<int>).Name); 

Assert.That(myinterface, Is.Not.Null); 
0
MyClass myc = new MyClass(); 

if (myc is MyInterface) 
{ 
    // it does 
} 

MyInterface myi = MyClass as IMyInterface; 
if (myi != null) 
{ 
    //... it does 
} 
+0

但我需要的类型,因为我将它添加到集合。 – 2010-03-26 10:29:46

1

使用名称,而不是全名

类型MyInterface的= myClass.GetType()。GetInterface(typeof运算(IMyInterface的)。 名称);

0

为什么你不使用“is”语句?测试这个:

class Program 
    { 
     static void Main(string[] args) 
     { 
      TestClass t = new TestClass(); 
      Console.WriteLine(t is TestGeneric<int>); 
      Console.WriteLine(t is TestGeneric<double>); 
      Console.ReadKey(); 
     } 
    } 

interface TestGeneric<T> 
    { 
     T myProperty { get; set; } 
    } 

    class TestClass : TestGeneric<int> 
    { 
     #region TestGeneric<int> Members 

     public int myProperty 
     { 
      get 
      { 
       throw new NotImplementedException(); 
      } 
      set 
      { 
       throw new NotImplementedException(); 
      } 
     } 

     #endregion 
    } 
相关问题