如何调用使用反射REF / OUT参数,方法 [英] How to invoke methods with ref/out params using reflection
本文介绍了如何调用使用反射REF / OUT参数,方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下,我有下面的类:
类牛{
公共静态布尔的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;
}
}
这篇关于如何调用使用反射REF / OUT参数,方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文