列表中的列表(关联)
本文关键字:列表 关联 | 更新日期: 2023-09-27 18:09:12
为了进一步加深我自己的理解,我正在复制一个简单的数据库-并且很难理解以下内容;
我有2类城镇和人民。一个城镇拥有许多People的实例,它们都是这样设置的;
public class Town
{
List<People> collectionOfPeople;
public string townName { get; set; }
public Town()
{
townName = "Cardiff";
collectionOfPeople = new List<People>();
collectionOfPeople.Add(new People("Daniel Smith"));
}
}
public class People
{
public string name { get; set; }
public People(string tmp_name)
{
name = tmp_name;
}
}
假设我所做的是正确的,城镇有1个值(卡迪夫),人民也有一个(丹尼尔史密斯)或…丹尼尔住在卡迪夫。
我试图显示住在镇上的人的名字。然后循环通过它们。(** =问题我认为)
private List<Town> townList;
private List<Town.People> peopleList; **
private void ShowData()
{
// Add to Text Box based on current Record
txt_town.Text = townList[0]).townName;
txt_name.Text = peopleList[0].name; **
}
以下是我的修改。为Town类中的collectionOfPeople提供公共访问修饰符
public class Town
{
public List<People> collectionOfPeople;
public string townName { get; set; }
}
之后,您可以访问城镇中的People实例。像这样:
private List<Town> townList = new List<Town>();
private void ShowData()
{
// Add to Text Box based on current Record
txt_town.Text = townList[0].townName;
txt_name.Text = townList[0].collectionOfPeople[0].name
}
你没有说,如果有的话,你会得到什么错误信息但我相信为了有
Town.People
你需要为Town类创建一个名为People的属性。我在你的代码中没有看到这个
还有,在你的行中有一个额外的括号:
txt_town.Text = townList[0].townName: //no ) after [0]