0

这些是我的对象类型:

public class Room
{


    public Giver Giver
    {
        get;
        set;
    }

    [XmlElement("Receiver")] 
    public List<Receiver> Receiver
    {
        get;
        set;
    }



}

 public class Receiver
{
    [XmlAttribute("type")]
    public string Type
    {
        get; set;
    }

    [XmlAttribute("Id")]
    public String Id
    {
        get; set;
    }


}

     class Program
{
    static void Main(string[] args)
    {

 List<Room> list = new List<Room>
        {
            new Room
            {

                Giver = new Giver{ Type="Generous",  PID="something"},
                Receiver = new List<Receiver>{new Receiver{Type="test1", Id="test2"},
                                              new Receiver{Type="test3", Id="test4"},
                                              new Receiver{Type="test5", Id="test6"}},




            }


        };

    }


}   

如果我声明 List eroom,我如何遍历 eroom 列表,其中声明了 Receiver 列表并访问 Receiver 的属性?

例如,我有:

List<Room> eroom;



 for (int i = 0; i < eroom.Count; i++)
        {
            Console.WriteLine("Giver Type: " + eroom[i].Giver.Type);
            Console.WriteLine("Giver PID: " + eroom[i].Giver.PID);

           //code below returns error
           Console.WriteLine("Receiver Id: " + eroom[i].Receiver.Id);

        }

如何在 for 循环中访问接收者的 ID?

4

2 回答 2

0
List<Room> eroom;
eroom.ForEach((room) =>{


            Console.WriteLine("Giver Type: " + room.Giver.Type);
            Console.WriteLine("Giver FNm: " + room.Giver.PID);
           room.Receiver.ForEach((receiver) =>{

            Console.WriteLine(receiver.Id);

             });

});
于 2012-06-18T14:55:42.620 回答
0

您需要在eroom其中的第二个循环。由于Receiver(变量,而不是类)是一个列表,因此每个列表中有多个 Id。你需要这样的东西:

foreach (Receiver r in eroom[i].Receiver)
    Console.WriteLine("Receiver Id: " + r.Id;

您还可以使用普通的 for 循环,使用 0 和 eroom[i].Reciever.Count 作为边界。

于 2012-06-18T14:56:39.547 回答