Finding out if a type implements a generic interface

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

    Using Anton Tykhyy's proposal, here is a small Extension Method to check if some type implements a generic interface with one given generic type parameters:

    public static class ExtensionMethods
    {
        /// 
        /// Checks if a type has a generic interface. 
        /// For example 
        ///     mytype.HasGenericInterface(typeof(IList<>), typeof(int)) 
        /// will return TRUE if mytype implements IList
        /// 
        public static bool HasGenericInterface(this Type type, Type interf, Type typeparameter)
        {
            foreach (Type i in type.GetInterfaces())
                if (i.IsGenericType && i.GetGenericTypeDefinition() == interf)
                    if (i.GetGenericArguments()[0] == typeparameter)
                        return true;
    
            return false;
        }
    }
    

提交回复
热议问题