【发布时间】:2011-05-11 18:28:48
【问题描述】:
我正在尝试编写从参数列表推断类型的代码,然后调用与这些参数匹配的方法。这非常有效,除非参数列表中有 null 值。
我想知道如何使Type.GetMethod 调用匹配函数/重载,即使在参数列表中有null 参数。
object CallMethodReflection(object o, string nameMethod, params object[] args)
{
try
{
var types = TypesFromObjects(args);
var theMethod = o.GetType().GetMethod(nameMethod, types);
return (theMethod == null) ? null : theMethod.Invoke(o, args);
}
catch (Exception ex)
{
return null;
}
}
Type[] TypesFromObjects(params object[] pParams)
{
var types = new List<Type>();
foreach (var param in pParams)
{
types.Add((param == null) ? null : param.GetType());
}
return types.ToArray();
}
主要问题行是types.Add((param == null) ? null : param.GetType());,这将导致GetMethod 调用失败,并在类型数组中显示null 值。
void Function1(string arg1){ }
void Function1(string arg1, string arg2){ }
void Function1(string arg1, string arg2, string arg3){ }
void Function2(string arg1){ }
void Function2(string arg1, int arg2){ }
void Function2(string arg1, string arg2){ }
/*1*/ CallMethodReflection(obj, "Function1", "String", "String"); // This works
/*2*/ CallMethodReflection(obj, "Function1", "String", null); // This doesn't work, but still only matches one overload
/*3*/ CallMethodReflection(obj, "Function2", "String", "String"); // This works
/*4*/ CallMethodReflection(obj, "Function2", "String", null); // This doesn't work, and I can see why this would cause problems
主要是,我正在尝试确定如何更改我的代码,以便/*2*/ 行也能正常工作。
【问题讨论】:
-
您使用的是 .NET 4 吗? .NET 4 已经支持动态关键字,它可以让你调用方法并且方法解析发生在运行时。
标签: c# reflection null