Finding out if a type implements a generic interface

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

    Using reflection (and some LINQ) you can easily do this:

    public static IEnumerable GetIListTypeParameters(Type type)
    {
        // Query.
        return
            from interfaceType in type.GetInterfaces()
            where interfaceType.IsGenericType
            let baseInterface = interfaceType.GetGenericTypeDefinition()
            where baseInterface == typeof(IList<>)
            select interfaceType.GetGenericArguments().First();
    }
    

    First, you are getting the interfaces on the type and filtering out only for those that are a generic type.

    Then, you get the generic type definition for those interface types, and see if it is the same as IList<>.

    From there, it's a simple matter of getting the generic arguments for the original interface.

    Remember, a type can have multiple IList implementations, which is why the IEnumerable is returned.

提交回复
热议问题