使用数据中的参数调用C#方法

gil*_*rtc 3 c# reflection

说,我有一个像这样的XML字符串,

<METHOD>foo</METHOD>
<PARAM1>abc</PARAM1>
<PARAM2>def</PARAM2>
...
<PARAM99>ghi</PARAM99>
<PARAM100>jkl</PARAM100>
Run Code Online (Sandbox Code Playgroud)

我有一个方法

void foo(String param1, String param2, ..., String param99, String param100)
{
...
}
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法让我将这个字符串映射到一个真正的方法调用,其中params匹配C#中方法的param名称?

Jon*_*eet 8

假设您知道类型,拥有它的实例,并且该方法实际上是公共的:

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);
Run Code Online (Sandbox Code Playgroud)

请注意,我在这里进行区分大小写的名称匹配,这对您的示例无效.如果你想要不区分大小写,那就稍微困难了,但仍然可行 - 我个人建议你尽可能使XML与方法匹配.

(如果它是非公共的,你需要为调用提供一些绑定标志GetMethod.)