Finding out if a type implements a generic interface

后端 未结 7 1785
深忆病人
深忆病人 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:26

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

提交回复
热议问题