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

如下,两个方法,签名唯一的区别在于参数带Out

如下,两个方法,签名唯一的区别在于参数带Out

C#
喵喵时光机 2023-01-02 18:14:19
例:public void Foo(out string value) {}public void Foo(string value){}在反射时如何区分这两个函数比如在Type.GetMethod获取的时候
查看完整描述

2 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

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

查看完整回答
反对 回复 2023-01-06
?
暮色呼如

TA贡献1853条经验 获得超9个赞

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 { 



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 }

 


查看完整回答
反对 回复 2023-01-06
  • 2 回答
  • 0 关注
  • 96 浏览

添加回答

举报

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