如何获取传递给已关闭/构造的泛型方法的参数值?
我已经有一段时间没有接触反射了。所有这些都曾经在我的脑海里,嗯,无论怎样。
class Program
{
static void Main(string[] args)
{
new ConcreteFoo().GenericMethod<int>(5);
Console.ReadKey();
}
}
class ConcreteFoo
{
public void GenericMethod<Q>(Q q)
{
var method = MethodInfo.GetCurrentMethod();
var parameters = method.GetParameters();
if (parameters.Length > 0)
foreach (var p in parameters)
Console.WriteLine("Type: {0}", p.ParameterType);
// That still prints Q as the type.
// I've tried GetGenericArguments as well. No luck.
// I want to know:
// 1) The closed type, i.e. the actual generic argument supplied by the caller; and
// 2) The value of that argument
}
public void GenericMethodWithNoGenericParameters<Q>()
{
// Same here
}
}
class GenericFoo<T>
{
public void NonGenericMethod(T t) { /* And here*/ }
public void GenericMethod<Q>(Q q) { /* And here */ }
}
更新
这个问题很荒谬,因此被提问者关闭了。他希望保留它,只是为了向孩子们展示爸爸有多愚蠢,如果他们最终成为C#程序员的话。
q.GetType()
? - Daniel Hilgarthtypeof(Q)
将会给你这个类型。 - Mehmet Ataşq.GetType()
会获取对象的实际类型,这意味着它可能是子类或者一个实现(如果Q
是一个接口)。typeof(Q)
将返回调用该方法时使用的泛型类型(无论传递的类型是什么,无论是明确指定:GenericMethod<object>(1)
(Q
为Object
),还是隐式指定:GenericMethod(1)
(Q
为Int32
))。 - Chris Sinclair