Finding out if a type implements a generic interface

后端 未结 7 1786
深忆病人
深忆病人 2020-12-01 05:49

Let\'s say I have a type, MyType. I want to do the following:

  1. Find out if MyType implements the IList interface, for some T.
  2. If the answer to (1) is y
7条回答
  •  遥遥无期
    2020-12-01 06:36

    As a helper method extension

    public static bool Implements(this Type type, I @interface) where I : class  
    {
        if(((@interface as Type)==null) || !(@interface as Type).IsInterface)
            throw new ArgumentException("Only interfaces can be 'implemented'.");
    
        return (@interface as Type).IsAssignableFrom(type);
    }
    

    example usage:

    var testObject = new Dictionary();
    result = testObject.GetType().Implements(typeof(IDictionary)); // true!
    

提交回复
热议问题