2012-02-18 53 views
0

可能重复:
Calling a function from a string in C#用C#字符串值调用一个方法

我想调用从另一个类的类的方法之一。 的事情是,我不知道提前方法名,我把它从外部API ..

例子:

class A 
    public class Whichone 
    { 
     public static string AA() { return "11"; } 
     public static string BB() { return "22"; } 
     public static string DK() { return "95"; } 
     public static string ZQ() { return "51"; } 
     .............. 
    } 


class B 
    public class Main 
    { 
     ........ 
     ........ 
     ........ 
     string APIValue = API.ToString(); 
     string WhichOneValue = [CALL(APIValue)]; 
    } 

让说的APIValue是BB然后WhichOneValue的值应该是莫名其妙22. 什么是正确的语法来做到这一点?

+3

使用[反射](http://www.codeproject.com/Articles/17269/Reflection-in-C-Tutorial)。 – 2012-02-18 10:30:55

回答

1

您可以使用反射:

string APIValue = "BB"; 

var method = typeof(Whichone).GetMethod(APIValue); 

// Returns "22" 
// As BB is static, the first parameter of Invoke is null 
string result = (string)method.Invoke(null, null); 
+0

明白了!非常感谢!! – user1199838 2012-02-18 10:37:20

+0

@ user1199838 if APIValue ==“BB”',它不返回null,而是一个'MethodInfo'实例。 – ken2k 2012-02-18 10:38:36

+1

@ user1199838如果答案满足您的需求,也许您应该考虑[接受它](http://meta.stackexchange.com/a/5235),所以人们会知道这个问题已经回答。 – ken2k 2012-02-18 10:52:45

1

这就是所谓的reflection。在你的情况下,代码应该是这样的:

string WhichOneValue = 
    (string)typeof(Whichone).GetMethod(APIValue).Invoke(null, null); 

一个反射的缺点是它比正常的方法调用慢。因此,如果分析显示调用这种方法对您而言太慢,则应考虑替代方法,如Dictionary<string, Action>Expression s。

+0

提及“Dictionary ”的+1,尽管在这个特例中它将是Dictionary > – Anastasiosyal 2012-02-18 12:59:42