C# 获取泛型接口的泛型参数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_15505341/article/details/102769637

定义一个泛型接口

    interface IGeneric<T>
    {
    }

假设Apple类继承了这个接口,并将T设为类GenericArgument

    class Apple : IGeneric<GenericArgument>
    {

    }

现在来获取这个[GenericArgument]

    using System.Linq;

    class Program
    {
        static Type[] GetGenericArguments(Type type, Type genericType)
        {
            return type.GetInterfaces() //取类型的接口
                .Where(i => IsGenericType(i)) //筛选出相应泛型接口
                .SelectMany(i => i.GetGenericArguments()) //选择所有接口的泛型参数
                .ToArray(); //ToArray

            bool IsGenericType(Type type1)
                => type1.IsGenericType && type1.GetGenericTypeDefinition() == genericType;
        }

        static void Main(string[] args)
        {
            var arguments = GetGenericArguments(typeof(Apple), typeof(IGeneric<>));
            foreach (var item in arguments)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }

成功输出

继承多次接口和接口有多个泛型参数同理,现在是合成一个List输出,按照需要修改源码即可

参考资料

  1. 博客园-吕毅-.NET/C# 判断某个类是否是泛型类型或泛型接口的子类型

猜你喜欢

转载自blog.csdn.net/qq_15505341/article/details/102769637