c#通过字符串值调用方法

本文关键字:值调用 方法 字符串 | 更新日期: 2023-09-27 18:24:58

可能重复:
从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。正确的语法是什么?

c#通过字符串值调用方法

您可以使用反射:

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);

这被称为反射。在您的情况下,代码看起来是这样的:

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

反射的缺点之一是它比正常的方法调用慢。因此,如果评测显示像这样调用方法太慢,您应该考虑其他选择,如Dictionary<string, Action>Expression