Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - Convert string to variable name

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 loop, I'd like set :

  • myvar1 to MyValue1
  • myvar2 to MyValue2

The C# Code :

protected string myvar1;
protected string myvar2;

The XML content look like this :

<parameters>
 <myvar1>MyValue1</myvar1>
 <myvar2>MyValue2</myvar2>
</parameters>

C# set variables :

    foreach (var item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
    {
        ??????
    }

Any idea ?

Thanks,

UPDATE 1: the value "field" in the loop is null all the time.

public class ParametersTest
{
    public string myvar1 { get; set; }
    public string myvar2 {get; set;}
}

var type = typeof(ParametersTest);
foreach (XmlNode item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
{

    var field = type.GetField(item.LocalName);
    field.SetValue(field, item.InnerText);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = @"<parameters>
            <MyVar1>MyValue1</MyVar1>
            <MyVar2>MyValue2</MyVar2>
           </parameters>";

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...