[英]How do you pass parameters by ref when calling a static method using reflection?
我正在使用反射調用對象上的靜態方法:
MyType.GetMethod("MyMethod", BindingFlags.Static).Invoke(null, new object[] { Parameter1, Parameter2 });
你如何通過 ref 而不是通過值傳遞參數? 我假設默認情況下它們是值。 第一個參數(數組中的“Parameter1”)應該是 ref,但我不知道如何以這種方式傳遞它。
對於引用參數(或 C# 中的 out),反射會將新值復制到與原始參數相同位置的對象數組中。 您可以訪問該值以查看更改的引用。
public class Example {
public static void Foo(ref string name) {
name = "foo";
}
public static void Test() {
var p = new object[1];
var info = typeof(Example).GetMethod("Foo");
info.Invoke(null, p);
var returned = (string)(p[0]); // will be "foo"
}
}
如果您調用Type.GetMethod
並僅使用BindingFlag
的BindingFlags.Static
,它將找不到您的方法。 刪除標志或添加BindingFlags.Public
它將找到靜態方法。
public Test { public static void TestMethod(int num, ref string str) { } }
typeof(Test).GetMethod("TestMethod"); // works
typeof(Test).GetMethod("TestMethod", BindingFlags.Static); // doesn't work
typeof(Test).GetMethod("TestMethod", BindingFlags.Static
| BindingFlags.Public); // works
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.