想象一下,我有以下类:
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? */);
解决方法
你可以这样做:
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; } }