Reading XML and executing functions dynamically using C#

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

I have a xml as below:



 

        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    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"]));
    }
    

提交回复
热议问题