我有这个界面及其实现:
public interface IInterface<TParam>
{
void Execute(TParam param);
}
public class Impl : IInterface<int>
{
public void Execute(int param)
{
...
}
}
如何使用 typeof(Impl)的反射来获取TParam( int here )类型?
答案 0 :(得分:3)
您可以使用一些反思:
// 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);