C#如何检查类是否实现了通用接口?

时间:2010-03-26 10:24:38

标签: c# generics interface types

如何获取实例的通用接口类型?

假设此代码:

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

5 个答案:

答案 0 :(得分:5)

要获取通用接口,您需要使用 Name 属性而不是 FullName 属性:

MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
                          .GetInterface(typeof(IMyInterface<int>).Name);

Assert.That(myinterface, Is.Not.Null);

答案 1 :(得分:1)

使用名称代替 FullName

输入myinterface = myClass.GetType()。GetInterface(typeof(IMyInterface)。 Name );

答案 2 :(得分:0)

MyClass myc = new MyClass();

if (myc is MyInterface)
{
    // it does
}

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

答案 3 :(得分:0)

为什么不使用“if”语句?测试一下:

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
    }

答案 4 :(得分:0)

尝试以下代码:

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