从字符串 C# 调用另一个命名空间的函数
Calling a function from another namespace from a string C#
我知道在 C# 中你可以通过这样做从字符串调用函数
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
但我想要这样的东西
CallMethodFromName("Console.WriteLine", "Hello, world!");
如何使用反射从另一个命名空间调用函数?
您可以使用 Type.GetType()
通过名称空间和名称获取类型。
...
Type thisType = Type.GetType("System.Console");
MethodInfo theMethod = thisType.GetMethod("WriteLine");
...
基于“Sticky bit”答案:
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!");
我知道在 C# 中你可以通过这样做从字符串调用函数
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
但我想要这样的东西
CallMethodFromName("Console.WriteLine", "Hello, world!");
如何使用反射从另一个命名空间调用函数?
您可以使用 Type.GetType()
通过名称空间和名称获取类型。
...
Type thisType = Type.GetType("System.Console");
MethodInfo theMethod = thisType.GetMethod("WriteLine");
...
基于“Sticky bit”答案:
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!");