C # method call with parameters from data

Say I have an XML string like this,

<METHOD>foo</METHOD>
<PARAM1>abc</PARAM1>
<PARAM2>def</PARAM2>
...
<PARAM99>ghi</PARAM99>
<PARAM100>jkl</PARAM100>

and i have a method

void foo(String param1, String param2, ..., String param99, String param100)
{
...
}

Is there any simple way to match this line with a real method call with parameters corresponding to method parameter names in C #?

+3
source share
3 answers

Assuming you know the type, you have an instance of it, and that the method is really 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);

Please note that here I am using a case-sensitive name that will not work with your sample. If you want to be case insensitive, this is a bit more complicated, but still doable - I personally would advise you that the XML conform to the method, if at all possible.

( , GetMethod.)

+8

- :

    public void Run(XmlElement rootElement)
    {
        Dictionary<string, string> xmlArgs = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase);
        foreach( XmlElement elem in rootElement )
            xmlArgs[elem.LocalName] = elem.InnerText;

        MethodInfo mi = this.GetType().GetMethod(xmlArgs["METHOD"]);

        List<object> args = new List<object>();
        foreach (ParameterInfo pi in mi.GetParameters())
            args.Add(xmlArgs[pi.Name]);

        mi.Invoke(this, args.ToArray());
    }
+2

edit If you need to match the names in the constructor. Just drop the constructor, as this is not a list of names / values, but just a list of required types of objects, and names are not needed. Use properties to match the xml element name and field in the class.

0
source

Source: https://habr.com/ru/post/1718309/


All Articles