我正在做的是通过反射调用方法。在我调用一些方法之前,让我们说它的名字将是FooMethod
,我需要创建argument
(我只在运行时才知道这个参数的类型)。所以我想用dynamic
这个字段来传递argument
的值。有没有像这样使用动态字段的方法?
例子:
class SampleClass
{
public string SomeField{get;set;}
}
class Foo
{
void Execute(string methodName, dynamic values)
{
var type = typeof(SampleClass);
var method = type.GetMethod(methodName);
var methodParameterType = method.GetParameters()[0].ParameterType;
var methodParameterProperties = methodParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
//just for example purpose assume that first property name is SomeField
if(values[methodParameterProperties[0].Name] != null)
{
// build argument here
}
}
}
使用的是:
dynamic a = new {SomeField = "someValue"};
var fooClass = new Foo();
fooClass.Execute("FooMethod",a);//here I'm getting exception
例外,我得到的那一刻:
Cannot apply indexing with [] to an expression of type 'object'
问题: 我应该怎么做?有没有办法允许检查这个值与索引而不创建字典?
什么是FooMethod? –
为什么不使用params而不是动态? – HimBromBeere
我使用经典反射代替动态。 – harry180