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(第一个通用参数);
删除代码>从执行
实现的末尾开始。