2014-11-17 46 views
0

我正在做的是通过反射调用方法。在我调用一些方法之前,让我们说它的名字将是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' 

问题: 我应该怎么做?有没有办法允许检查这个值与索引而不创建字典?

+0

什么是FooMethod? –

+1

为什么不使用params而不是动态? – HimBromBeere

+0

我使用经典反射代替动态。 – harry180

回答

0

尝试使用ExpandoObject而不是动态。你不能索引它,但你不能创建你的字典。

public void Execute(string methodName, ExpandoObject values) 
    { 
     // ... 

     if(values.Any(x => x.Key == methodParameterProperties[0].Name)) 
     { 
      var value = values.First(x => x.Key == methodParameterProperties[0].Name).Value; 
      // build argument here (based on value) 

     } 
    } 
0

你和一个单场,SomeField分配一个匿名类的实例,以a,然后尝试索引它,仿佛它是一个数组。这是行不通的。

但是,MethodInfo.Invoke()接受一个对象数组作为参数,所以根本就不需要动态。将values参数的类型更改为object[],并将其传递给Invoke。所以:

public class MyClass 
{ 
    public void MyMethod(string s) 
    { 
    } 
} 

public object Execute(object obj, string methodName, object[] arguments) 
{ 
    Type type = obj.GetType(); 
    MethodInfo methodInfo = type.GetMethod(methodName); 
    return methodInfo.Invoke(obj, arguments); 
} 

您还可以将params符添加到arguments所以可以这样调用:

Execute(someObject, "someObjectMethod", arg1, arg2, arg3); 

你需要确保你传递的参数是正确的类型,否则Invoke会抛出一个ArgumentException。另外,如果给定的对象没有给定名称的方法,GetMethod将返回null。您可能还想检查该方法所需参数的数量,具体取决于您打算如何以及在何处使用此代码。

相关问题