如何使用reflection调用ref / out参数的方法
想象一下,我有以下课程:
class Cow { public static bool TryParse(string s, out Cow cow) { ... } }
是否可以通过reflection调用TryParse
? 我知道基础知识:
var type = typeof(Cow); var tryParse = type.GetMethod("TryParse"); var toParse = "..."; var result = (bool)tryParse.Invoke(null, /* what are the args? */);
你可以这样做:
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; } }