【问题标题】:How to invoke methods with ref/out params using reflection如何使用反射调用带有 ref/out 参数的方法
【发布时间】:2010-02-21 04:19:08
【问题描述】:

假设我有以下课程:

class Cow {
    public static bool TryParse(string s, out Cow cow) {
        ...
    }
}

是否可以通过反射调用TryParse?我知道基础知识:

var type = typeof(Cow);
var tryParse = type.GetMethod("TryParse");

var toParse = "...";

var result = (bool)tryParse.Invoke(null, /* what are the args? */);

【问题讨论】:

  • 这正是我要问的问题,甚至是方法名称:D

标签: c# .net reflection


【解决方案1】:

你可以这样做:

static void Main(string[] args)
{
    var method = typeof (Cow).GetMethod("TryParse");
    var cow = new Cow();           
    var inputParams = new object[] {"cow string", cow};
    method.Invoke(null, inputParams); 
    // out parameter value is then set in inputParams[1]
    Console.WriteLine( inputParams[1] == null ); // outputs True
}

class Cow
{
    public static bool TryParse(string s, out Cow cow) 
    {
        cow = null; 
        Console.WriteLine("TryParse is called!");
        return false; 
    }
}

【讨论】:

  • 请注意:a) 调用 TryParse 方法不需要 'Cow' 实例,只需传递 null 值即可。 b) inputParams[1]中返回解析后的'Cow',上面代码中的'cow'保持不变。
  • 因此这就是答案,全面 +1。
猜你喜欢
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2011-08-29
相关资源
最近更新 更多