想象一下,我有下面的类:
类牛{
公共静态布尔的TryParse(字符串s,出奶牛牛){
...
}
}
是否有可能通过反射调用的TryParse
?我知道的基本知识:
VAR类型= typeof运算(牛);
变种的TryParse = type.GetMethod(的TryParse);
VAR toParse =...;
VAR的结果=(布尔)tryParse.Invoke(NULL,/ *哪些的args * /?);
解决方案
您可以做这样的事情:
静态无效的主要(字串[] args)
{
VAR方法= typeof运算(牛).GetMethod(的TryParse);
VAR牛=新牛();
VAR inputParams =新的对象[] {牛绳,牛};
method.Invoke(NULL,inputParams);
}
一流的奶牛
{
公共静态布尔的TryParse(字符串s,出奶牛牛)
{
牛= NULL;
Console.WriteLine(的TryParse称为!);
返回false;
}
}
Imagine I have the following class:
class Cow {
public static bool TryParse(string s, out Cow cow) {
...
}
}
Is it possible to call TryParse
via reflection? I know the basics:
var type = typeof(Cow);
var tryParse = type.GetMethod("TryParse");
var toParse = "...";
var result = (bool)tryParse.Invoke(null, /* what are the args? */);
解决方案
You can do something like this:
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;
}
}