0

我有一个类描述一个人的名字和姓氏,如下所示:

public class Person
{
    string firstname;
    string lastname;
}

还有一个列表,我在其中添加了Person这样的项目:

List<Person> PersonList;

我使用 Xml 序列化后填写列表。当我检查列表容量时,一切似乎都很好。

我的问题是,如何从列表中访问一个人的名字或姓氏?

4

1 回答 1

5

首先,您的属性Person是隐式私有的,因为您没有提供访问修饰符。让我们解决这个问题:

public class Person { 
    public string firstname;
    public string lastname;
}

然后,您需要索引到列表中的一个元素,然后您可以访问列表中特定元素的特定属性;

int index = // some index
// now, PersonList[index] is a Person
// and we can access its accessible properties
Console.WriteLine(PersonList[index].firstname);

当然,你必须确保它在你的列表中index是有效index的,也就是说,它满足0 <= index < PersonList.Count.

于 2013-07-27T13:30:34.830 回答