簡體   English   中英

從字符串 C# 從另一個命名空間調用 function

[英]Calling a function from another namespace from a string C#

我知道在 C# 中,您可以通過這樣做從字符串中調用 function

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

但我想要這樣的東西

CallMethodFromName("Console.WriteLine", "Hello, world!");

如何使用反射從另一個命名空間調用 function?

您可以使用Type.GetType()通過命名空間和名稱獲取類型。

...
Type thisType = Type.GetType("System.Console");
MethodInfo theMethod = thisType.GetMethod("WriteLine");
...

基於“粘性位”答案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM