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

6
如何获取实例的通用接口类型?
假设有以下代码:
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个回答

5
为了获得通用接口,您需要使用Name属性而不是FullName属性:
MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
                          .GetInterface(typeof(IMyInterface<int>).Name);

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

1

使用Name代替FullName

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


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

0
MyClass myc = new MyClass();

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

或者

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

但是我需要类型,因为我要将它添加到集合中。 - theSpyCry

0

为什么不使用“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
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接