调用C#方法与参数数据 [英] Calling C# method with parameters from data
问题描述
我说,我有一个这样的XML字符串,
Say, I have an XML String like this,
<METHOD>foo</METHOD>
<PARAM1>abc</PARAM1>
<PARAM2>def</PARAM2>
...
<PARAM99>ghi</PARAM99>
<PARAM100>jkl</PARAM100>
和我有一个方法
void foo(String param1, String param2, ..., String param99, String param100)
{
...
}
有没有我这个字符串映射到相匹配的方法的参数名称PARAMS一个真正的方法调用任何简单的方法?C#
Is there any easy way for me to map this string to a real method call with the params matching the param names of the method in C#?
推荐答案
假设你知道类型,有它的一个实例,并且该方法实际上是公开:
Assuming you know the type, have an instance of it, and that the method is actually public:
string methodName = parent.Element("METHOD").Value;
MethodInfo method = type.GetMethod(methodName);
object[] arguments = (from p in method.GetParameters()
let arg = element.Element(p.Name)
where arg != null
select (object) arg.Value).ToArray();
// We ignore extra parameters in the XML, but we need all the right
// ones from the method
if (arguments.Length != method.GetParameters().Length)
{
throw new ArgumentException("Parameters didn't match");
}
method.Invoke(instance, arguments);
请注意,我做区分大小写的名称匹配在这里,它不会与你的样品工作。如果你想不区分大小写,这是稍硬,但还是可行的 - 我个人建议你使XML匹配,如果在所有可能的方法。
Note that I'm doing case-sensitive name matching here, which wouldn't work with your sample. If you want to be case-insensitive it's slightly harder, but still doable - personally I'd advise you to make the XML match the method if at all possible.
(如果是非公您需要提供一些绑定标志来调用<code> GetMethod )
(If it's non-public you need to provide some binding flags to the call to GetMethod
.)
这篇关于调用C#方法与参数数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!