从从泛型接口继承的类中获取泛型参数的类型

本文关键字:泛型 参数 类型 获取 泛型接口 继承 | 更新日期: 2023-09-27 18:25:43

我有这个接口及其实现:

public interface IInterface<TParam>
{
    void Execute(TParam param);
}
public class Impl : IInterface<int>
{
    public void Execute(int param)
    {
        ...
    }
}

如何使用(Impl)类型的反射来获得TParam(int此处)类型?

从从泛型接口继承的类中获取泛型参数的类型

您可以使用一点反射:

// your type
var type = typeof(Impl);
// find specific interface on your type
var interfaceType = type.GetInterfaces()
    .Where(x=>x.GetGenericTypeDefinition() == typeof(IInterface<>))
    .First();
// get generic arguments of your interface
var genericArguments = interfaceType.GetGenericArguments();
// take the first argument
var firstGenericArgument = genericArguments.First();
// print the result (System.Int32) in your case
Console.WriteLine(firstGenericArgument);