Convert string to variable name

前端 未结 5 489
逝去的感伤
逝去的感伤 2020-12-20 16:53

I have an XML file, I have a node and I read all ChildNodes. The name of the childNode match to a variable I have to set with the value of this childNode.

In the loo

5条回答
  •  清歌不尽
    2020-12-20 17:33

    You can do it using Reflection:

    var type = typeof(SomeClass);
    var field = type.GetField(item.Name);
    field.SetValue(null, item.InnerText);
    

    RE: UPDATE 1

    var parameters = new ParametersTest();
    var type = parameters.GetType();
    
    var s = @"
                MyValue1
                MyValue2
               ";
    
    var xmlParamInstallation = new XmlDocument();
    xmlParamInstallation.LoadXml(s);
    
    foreach (XmlNode item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
    {
    
        var field = type.GetProperty(item.LocalName);
        field.SetValue(parameters, item.InnerText, null);
    }
    

提交回复
热议问题