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

4

我有这个接口及其实现:

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

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

如何使用反射从 typeof(Impl) 获取 TParam (这里是 int 类型) 类型?

从您的Execute实现中删除末尾的; - Orel Eraki
1个回答

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接