2010-03-26 30 views
6

¿Cómo obtener el tipo de interfaz genérica para una instancia?C# ¿Cómo verificar si una clase implementa una interfaz genérica?

Supongamos que este código:

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); 

Respuesta

5

Con el fin de obtener la interfaz genérica es necesario utilizar la propiedad Nombre en lugar de la propiedad NombreCompleto:

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 
} 

o

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

Pero necesito el tipo, porque lo estoy agregando a una Colección. –

1

Uso Nombre en lugar de NombreCompleto

Tipo MyInterface = myClass.GetType(). GetInterface (typeof (IMyInterface). Nombre);

0

¿Por qué no utiliza la instrucción "is"? Pruebe esto:

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 
    } 
Cuestiones relacionadas