想象一下,我有以下课程:
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? */);
答案 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;
}
}