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

Fra*_*ger 10 .net c# reflection

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

class Cow {
    public static bool TryParse(string s, out Cow cow) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

可以TryParse通过反思来打电话吗?我知道基础知识:

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

var toParse = "...";

var result = (bool)tryParse.Invoke(null, /* what are the args? */);
Run Code Online (Sandbox Code Playgroud)

aza*_*arp 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; 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意:a)调用TryParse方法不需要'Cow'实例,只需传递null值即可.b)解析的'Cow'在inputParams [1]中返回,上面代码中的'cow'保持不变. (7认同)