[英]C# How to check if a class implements generic 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);
為了獲得通用接口,您需要使用Name屬性而不是FullName屬性:
MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
.GetInterface(typeof(IMyInterface<int>).Name);
Assert.That(myinterface, Is.Not.Null);
使用名稱,而不是全名
鍵入MyInterface的= myClass.GetType()GetInterface(typeof運算(IMyInterface的)名稱。)。
MyClass myc = new MyClass();
if (myc is MyInterface)
{
// it does
}
或者
MyInterface myi = MyClass as IMyInterface;
if (myi != null)
{
//... it does
}
為什么不使用“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
}
試試下面的代碼:
public static bool ImplementsInterface(Type type, Type interfaceType)
{
if (type == null || interfaceType == null) return false;
if (!interfaceType.IsInterface)
{
throw new ArgumentException("{0} must be an interface type", nameof(interfaceType));
}
if (interfaceType.IsGenericType)
{
return interfaceType.GenericTypeArguments.Length > 0
? interfaceType.IsAssignableFrom(type)
: type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
}
return type.GetInterfaces().Any(iType => iType == interfaceType);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.