Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从从泛型接口继承的类中获取泛型参数的类型_C#_Generics_Reflection - Fatal编程技术网

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

C# 从从泛型接口继承的类中获取泛型参数的类型,c#,generics,reflection,C#,Generics,Reflection,我有这个接口及其实现: public interface IInterface<TParam> { void Execute(TParam param); } public class Impl : IInterface<int> { public void Execute(int param) { ... } } 公共接口接口 { 无效执行(TParam参数); } 公共类Impl:i接口 { 公共void执行(int

我有这个接口及其实现:

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

public class Impl : IInterface<int>
{
    public void Execute(int param)
    {
        ...
    }
}
公共接口接口
{
无效执行(TParam参数);
}
公共类Impl:i接口
{
公共void执行(int参数)
{
...
}
}

如何使用来自typeof(Impl)的反射获取TParam(int here)类型?

您可以使用一些反射:

// 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);
//您的类型
变量类型=类型(Impl);
//查找类型上的特定接口
var interfaceType=type.GetInterfaces()
.其中(x=>x.GetGenericTypeDefinition()==typeof(IInterface))
.First();
//获取接口的通用参数
var genericArguments=interfaceType.GetGenericArguments();
//以第一个论点为例
var firstGenericArgument=genericArguments.First();
//在您的案例中打印结果(System.Int32)
Console.WriteLine(第一个通用参数);

删除
执行
实现的末尾开始。