繁体   English   中英

C#如何检查一个类是否实现了泛型接口?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM