如何获取实例的通用接口(interface)类型?
假设这段代码:
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);
最佳答案
为了获得通用接口(interface),您需要使用Name 属性而不是FullName 属性:
MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
.GetInterface(typeof(IMyInterface<int>).Name);
Assert.That(myinterface, Is.Not.Null);
关于C# 如何检查一个类是否实现了泛型接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2522461/