如何使用反射调用ref / out参数的方法

时间:2010-02-21 04:19:08

标签: c# .net reflection

想象一下,我有以下课程:

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? */);

1 个答案:

答案 0 :(得分:6)

您可以这样做:

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); 
}

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