2013-07-27 40 views
0

我描述一个人的名字和姓氏像这样一类:访问列表项类型的类的

public class Person 
{ 
    string firstname; 
    string lastname; 
} 

和一个列表中,我添加Person项目是这样的:

List<Person> PersonList; 

我使用Xml序列化后填充列表。当我检查列表容量时,一切似乎都没有问题。

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

回答

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,也就是说,它satifies 0 <= index < PersonList.Count