在对象列表中分配属性

时间:2016-06-05 17:48:37

标签: c# list foreach

我有一个对象列表,其中包含需要分配的多个属性。

虽然我怀疑数据的来源很重要,但我会将其包含在背景中。我正在使用foreach循环从XmlDocument中的选择节点读取属性列表。我已经创建了一个循环迭代器i,我正在尝试根据attribute.Name和attribute.Value将值分配给每个对象的属性。

  // Reads each attribute: label, type, number etc...
  foreach (XmlNode node in myValues.SelectNodes("//Properties"))
  {
    foreach (XmlAttribute attribute in node.Attributes)
    {

      //this iterates through the attributes just fine
      //and in each iteration attribute.Name = the property
      //I want to set and attribute.Value = the value to set it to.

      myList[i].label = attribute.Value; //works

      //what I'd like to do something like
      myList[i].attribute.Name = attribute.Value;

这让我疯了。必须有一些参考attribute.Name的值?

3 个答案:

答案 0 :(得分:2)

您可以使用反射按名称设置属性,例如:

var current = myList[i];
current.GetType().GetProperty(attribute.Name).SetValue(current, attribute.Value);

答案 1 :(得分:1)

您可以将XML文档反序列化为POCO对象。我个人喜欢这种方法而不是反思,它使我能够更好地控制正在发生的事情并且更容易看到。

最大的问题是创建要反序列化的POCO对象。

Visual Studio的一个很酷的功能(这是2015年,不确定何时推出),你可以'将XML粘贴为类'

  1. 将目标XML文档复制到您的复制缓冲区(ctrl + c)
  2. Image showing the Visual Studio Menu option of 'Paste XML as Classes' in the Edit menu's Paste Special list.

    1. 在Visual Studio中打开一个新的类文件。
    2. 在命名空间内部而不是他的类(这将创建类,使你的光标。
    3. 使用菜单编辑 - >;选择性粘贴 - >将XML粘贴为类
    4. 然后你应该看到Visual Studio生成的类。 注意:我发现当它看到一个数字时,如果数字低于255,它会将该字段创建为byte。我不得不进入后记并将其更改为int s。这是一个快速查找和替换,但如果您遇到反序列化问题,这是一个重要的步骤。

      生成类后,这是一个简单的反序列化问题,下面是一些示例代码:

      //Object to deserialize into
      MySerializableClass myObject;
      
      //Create deserializer for object
      XmlSerializer mySerializer = new XmlSerializer(typeof(MySerializableClass));
      
      //Open XML file to read
      using (FileStream myFileStream = new FileStream("myFileName.xml", FileMode.Open))
      {
        //Deserialize XML into your POCO object
        myObject = (MySerializableClass) mySerializer.Deserialize(myFileStream);
      }
      

      然后你可以使用该对象并获得你想要的值。

答案 2 :(得分:0)

首先需要找到要在循环中更新属性的对象。您可以使用LINQ,因为在这篇文章中已经多次回答了@SO:

Using LINQ, how do I find an object with a given property value from a List?

   Question question14 = _mQuestions.FirstOrDefault(q => q.QuestionID == 14);
   if (question14 != null)
       question14.QuestionAnswer = "Some Text";

然后你可以更新属性......