Reading XML and executing functions dynamically using C#

前端 未结 2 430
花落未央
花落未央 2021-01-26 19:18

I have a xml as below:



 

        
相关标签:
2条回答
  • 2021-01-26 19:52

    I've done something broadly similar for a project I'm working on. From a high level perspective, if you can assume that the Action Word is exactly the name of a method in some assembly, then you can use reflection to get a MethodInfo corresponding to the actual function. You can then invoke the function, passing in the appropriate parameters to the method.

    The one catch here is how to specify the parameters. Since there will be a variable number of parameters, you need to use a data structure which is capable of handling the variable list. I'd suggest using a Dictionary to pass the parameters.

    Ok, so assuming that you can identify and load the appropriate assembly, proceed something like this:

    foreach Action:

    • retrieve the value of the Word attribute into actionWordString
    • create a new Dictionary instance
    • foreach Parameter in Action:
    • retrieve the Name and Value attribute values
    • add a new entry in your Dictionary: i.e. dict[nameString] = valueString
    • use reflection to find the MethodInfo with the same name as the actionWordString and which also takes a Dictionary as a parameter
    • invoke the Method, passing in the Dictionary you previously created and populated.

    It takes as much prose to describe as it does code to implement. One of the harder things, at least as I find it, is to load or access the Type of the Assembly which contains the methods. Also, it would probably be best to implement the methods as static, so that you don't have to be concerned about creating an instance of the handler class.

    0 讨论(0)
  • 2021-01-26 20:06
    object obj = this; //your object containing methods
    XDocument xDoc = XDocument.Parse(xml);
    Type type = obj.GetType(); 
    
    foreach (var action in xDoc.Descendants("Action"))
    {
        MethodInfo mi = type.GetMethod(action.Attribute("Word").Value);
    
        var dict =  action.Descendants().ToDictionary(
                                             d=>d.Attribute("Name").Value,
                                             d=>d.Attribute("Value").Value);
    
        object[] parameters = mi.GetParameters()
            .Select(p => Convert.ChangeType(dict[p.Name],p.ParameterType))
            .ToArray();
    
        var expectedResult = mi.Invoke(obj, parameters);
    
        Debug.Assert(expectedResult.Equals(dict["expectedResult"]));
    }
    
    0 讨论(0)
提交回复
热议问题