C#如何通过反射调用带有ref或者out的参数的方法

时间:2023-03-08 19:29:15

写这篇博客,原起今天CyljXu问我一个问题:如何通过反射调用带有ref或者out的参数的方法?想着可能其他人也会遇到这个问题,权且记录下来,以备后行者搜索到。

这个在MSDN上有解释,参考 MethodBase.Invoke方法 。



Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/ -->public Object Invoke( Object obj, Object[] parameters)

参数

obj 类型:System.Object

对其调用方法或构造函数的对象。如果方法是静态的,则忽略此参数。如果构造函数是静态的,则此参数必须为 null 引用(在 Visual Basic
中为 Nothing )
或定义该构造函数的类的实例。

parameters
类型: System.Object[]

调用的方法或构造函数的参数列表。这是一个对象数组,这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。如果没有任何参数,则 parameters 应为 null 引用(在 Visual Basic 中为 Nothing ) 。

如果此实例所表示的方法或构造函数采用 ref
参数(在 Visual Basic 中为 ByRef
),使用此函数调用该方法或构造函数时, 该参数不需要任何特殊属性
。如果数组中的对象未用值来显式初始化,则该对象将包含该对象类型的默认值。对于引用类型的元素,该值为 null 引用(在 Visual Basic
中为 Nothing ) 。对于值类型的元素,该值为 0、0.0 或
false
,具体取决于特定的元素类型。

那么该如何调用并处理传值呢?请看如下示例:



Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/ -->1 class Program

2 {

3 static void Main(string[] args)

4 {

5

string content = "main"; //#1 variable

6 MethodInfo testMethod = typeof(Program).GetMethod("TestMethod",

7 BindingFlags.Static | BindingFlags.NonPublic);

8 if (testMethod != null)

9 {

10 // Following way can not take content back.

11 // -------------------------------------

12 testMethod.Invoke(null, new object[] { content /* #1 variable */ });

13 Console.WriteLine(content); // #1 variable, Output is: main

14 // -------------------------------------

15

16

17 object[] invokeArgs = new object[] { content /* #1 variable */ };

18 testMethod.Invoke(null, invokeArgs);

19 content = (string)invokeArgs[0]; // #2 variable, bypass from invoke, set to content.

20 Console.WriteLine(content); // #2 variable, Output is: test

21 }

22 }

23

24 static void TestMethod(ref string arg)

25 {

26 arg = "test"; // #2 variable, wanna bypass to main process.

27 }

28 }