为了账号安全,请及时绑定邮箱和手机立即绑定

求助,关于C#反射签名中带Out参数的函数的问题,麻烦大神帮忙看看!

求助,关于C#反射签名中带Out参数的函数的问题,麻烦大神帮忙看看!

C# C
临摹微笑 2021-11-18 15:11:51
两个方法,签名唯一的区别在于参数带Out 例:public void Foo(out string value) {}public void Foo(string value){}在反射时如何区分这两个函数比如在Type.GetMethod获取的时候
查看完整描述

2 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

Type.GetMethod可以得到一个MethodInfo对象,MethodInfo对象有一个方法是GetParameters即得到ParameterInfo数组,ParameterInfo对象有一个属性是IsOut。

已知foo的函数原型么?如果已知的话可以用GetMethod(string, Type[])这个重载。
比如你提到的有这样一个类:
class a
{
public void foo(string value);
public void foo(out string value);
}

如果想获得上面那一个方法,用这个语句:

1

type.GetMethod("foo", new Type[] { typeof(string) });

如果想获得下面那一个方法,用这个语句:

1

type.GetMethod("foo", new Type[] { typeof(string).MakeByRefType() });
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 }



查看完整回答
反对 回复 2021-11-23
?
catspeake

TA贡献1111条经验 获得超0个赞

Type.GetMethod可以得到一个MethodInfo对象,MethodInfo对象有一个方法是GetParameters即得到ParameterInfo数组,ParameterInfo对象有一个属性是IsOut。

查看完整回答
反对 回复 2021-11-23
  • 2 回答
  • 0 关注
  • 186 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信