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

mtk*_*nko 4 c# generics reflection

我有这个接口及其实现:

public interface IInterface<TParam>
{
    void Execute(TParam param);
}

public class Impl : IInterface<int>
{
    public void Execute(int param)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

dot*_*tom 5

您可以使用一些反射:

// 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);
Run Code Online (Sandbox Code Playgroud)