pal*_*wim 8 c# reflection null
我正在尝试编写将从参数列表中推断出类型的代码,然后调用与这些参数匹配的方法.这非常有效,除非参数列表中包含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();
}
Run Code Online (Sandbox Code Playgroud)
主要问题是types.Add((param == null) ? null : param.GetType());,这将导致GetMethod调用失败,null并在types数组中使用值.
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
Run Code Online (Sandbox Code Playgroud)
主要是,我正在尝试确定如何更改我的代码,以便该行也能/*2*/正常工作.
GetMethod调用有一些覆盖,它使用从Binder类派生的对象.这允许您根据传递的实际参数覆盖默认方法绑定并返回要使用的方法.这基本上是另外两个答案正在做的事情.这里有一些示例代码:
http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx
未提及的选项是使用Fasterflect,这是一个旨在使反射任务更容易,更快速(通过IL生成)的库.
要调用给定命名参数字典的方法(或具有应该用作参数的属性的对象),可以调用这样的最佳匹配:
obj.TryCallMethod( "SomeMethod", argsDictionary );
obj.TryCallMethod( "AnotherMethod", new { Foo = "Bar" } );
Run Code Online (Sandbox Code Playgroud)
如果你只有参数值及其顺序,你可以使用另一个重载:
obj.TryCallMethodWithValues( "MyMethod", 42, "foo", "bar", null, 2.0 );
Run Code Online (Sandbox Code Playgroud)
PS:您需要从源代码控制中获取最新的位以利用TryCallMethodWithValues扩展.
免责声明:我是Fasterflect项目的贡献者.
| 归档时间: |
|
| 查看次数: |
3837 次 |
| 最近记录: |