C # How to check if a class implements a common interface?

How to get a generic interface type for an instance?

Assume this code:

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); 
+6
generics c # types interface
source share
4 answers

To get a common interface, you need to use the Name property instead of the FullName property:

 MyClass myClass = new MyClass(); Type myinterface = myClass.GetType() .GetInterface(typeof(IMyInterface<int>).Name); Assert.That(myinterface, Is.Not.Null); 
+5
source share

Use Name instead of FullName

Enter myinterface = myClass.GetType (). GetInterface (typeof (IMyInterface). Name );

+1
source share
 MyClass myc = new MyClass(); if (myc is MyInterface) { // it does } 

or

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

Why don't you use the eat instruction? Check this:

 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 } 
0
source share

All Articles