C# 类的访问列表项类型
我有一个类,它描述了一个人的名字和姓氏,如下所示:C# 类的访问列表项类型,c#,list,C#,List,我有一个类,它描述了一个人的名字和姓氏,如下所示: public class Person { string firstname; string lastname; } List<Person> PersonList; 还有一个列表,我在其中添加了一个Person项,如下所示: public class Person { string firstname; string lastname; } List<Person> PersonL
public class Person
{
string firstname;
string lastname;
}
List<Person> PersonList;
还有一个列表,我在其中添加了一个Person
项,如下所示:
public class Person
{
string firstname;
string lastname;
}
List<Person> PersonList;
列出个人列表;
我在使用Xml序列化后填写了列表。当我查看列表时,一切似乎都正常
我的问题是,如何从列表中访问persons firstname或lastname?首先,您在
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);
当然,您必须确保
索引
是列表中有效的索引
,也就是说,它满足0首先,您在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);
当然,您必须确保索引
在列表中是有效的索引
,也就是说,它满足0