我知道在 C# 中你可以通过这样做从字符串调用一个函数
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
但我想要这样的东西
CallMethodFromName("Console.WriteLine", "Hello, world!");
如何使用反射从另一个命名空间调用函数?
答案 0 :(得分:1)
您可以使用 Type.GetType()
通过命名空间和名称获取类型。
...
Type thisType = Type.GetType("System.Console");
MethodInfo theMethod = thisType.GetMethod("WriteLine");
...
答案 1 :(得分:1)
基于“粘滞位”答案:
Type thisType = Type.GetType("System.Console");
MethodInfo theMethod = thisType.GetMethod("WriteLine");
theMethod.Invoke(null, new object[1] { "Hello" });
但是你必须小心方法重载,因为那样你可以得到
System.Reflection.AmbiguousMatchException
此外,这种方法并不是最好的,它是设计问题的标志。 要记住的另一件事是使用“nameof”运算符来告诉命名空间名称和方法,这是为了避免魔术字符串。 将此应用于我给出的示例:
Type thisType = Type.GetType(nameof(System) + "." + nameof(Console));
MethodInfo theMethod = thisType.GetMethod(nameof(Console.WriteLine));
theMethod.Invoke(null, new object[1] { "Hello" });
然后是调用者:
CallMethodFromName(nameof(Console) + "." + nameof(Console.WriteLine), "Hello, world!");