2010-07-20 17 views
1

我必须调用名称来自配置文件的方法。我可以使用Reflection.MethodInfo.Invoke()方法实现此目的。但我的场景是所有这些方法应该是相同的签名。我可以使用代表实现它吗?但我怎么能添加一个方法名称存储在配置文件中的代表?如何将方法名称从配置文件添加到委托?

回答

1

如果您愿意,您可以创建可重复使用的委托。给我喜欢的类型:

public class MyClass 
{ 
    public void DoSomething(string argument1, int argument2) 
    { 
     Console.WriteLine(argument1); 
     Console.WriteLine(argument2); 
    } 
} 

我可以这样做:

Action<object, MethodInfo, string, int> action = 
    (obj, m, arg1, arg2) => m.Invoke(obj, new object[] { arg1, arg2 }); 

,并调用它为:

var method = typeof(MyClass).GetMethod("DoSomething"); 
var instance = new MyClass(); 

action(instance, method, "Hello", 24); 

如果你知道你的方法有一个返回类型,你可以这样做与System.Func代表:

public class MyClass 
{   
    public string DoSomething(string argument1, int argument2) 
    { 
     return string.Format("{0} {1}", argument1, argument2); 
    } 
} 

Func<object, MethodInfo, string, int, string> func = 
    (obj, m, arg1, arg2) => (string)m.Invoke(obj, new object[] { arg1, arg2 }); 

string result = func(instance, method, "Hello", 24); 
+0

OM G ..... ...... – leppie 2010-07-20 11:04:49

+0

不错!用例子很清楚。 – 2010-07-20 11:29:11

相关问题