猿问

如何将项目添加到列表

我有班级的人,城市和街道。编号它的门牌号。我面临这样一个问题,即一个人不仅可以住在 1 个城市,还可以住在 2 个(纽约和洛杉矶)。如何向人添加新城市。


var live = new List<Live>();

    lives.Add(new Live

    {

        Person = new Person

        {

            FirstName = "Joe",

            LastName = "Doe"

        },

        City = new City

        {

            Name = "NY",

        },

        Number = 31

    });


慕妹3146593
浏览 151回答 2
2回答

慕标5832272

在Live课堂上,将变量设为Citya City[],允许某人居住在多个城市。City City;到City[] Cities;然后你可以改变你的代码看起来有点像这样......var live = new List<Live>();lives.Add(new Live{&nbsp; &nbsp; Person = new Person&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; FirstName = "Joe",&nbsp; &nbsp; &nbsp; &nbsp; LastName = "Doe"&nbsp; &nbsp; },&nbsp; &nbsp; Cities = new City[]&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; new City {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = "LA"&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; new City {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = "NY"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; Number = 31});编辑:如果你想Cities成为一个List<City>那么你可以修改你的代码看起来像这样......var live = new List<Live>();lives.Add(new Live{&nbsp; &nbsp; Person = new Person&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; FirstName = "Joe",&nbsp; &nbsp; &nbsp; &nbsp; LastName = "Doe"&nbsp; &nbsp; },&nbsp; &nbsp; Cities = new List<City>(&nbsp; &nbsp; new City[]&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; new City {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = "LA"&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; new City {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = "NY"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }),&nbsp; &nbsp; Number = 31});

GCT1015

您可以将 City 改为 Cities (城市列表)。var live = new List<Live>();lives.Add(new Live{&nbsp; &nbsp; Person = new Person&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; FirstName = "Joe",&nbsp; &nbsp; &nbsp; &nbsp; LastName = "Doe"&nbsp; &nbsp; },&nbsp; &nbsp; Cities = new List<City>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; new City&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = "NY",&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; new City&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = "LA",&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; Number = 31});为了编译,你的 Person 类应该像这样定义:public class Live{&nbsp; &nbsp; public Person Person { get; set; }&nbsp; &nbsp; public List<City> Cities { get; set; }&nbsp; &nbsp; public int Number;}另外,根据您的评论,如果您想要Number每个城市,那么我能想象的最简单的解决方案是将 Number 从 Person 类移动到 City 类。最终,这取决于您需要准确建模的内容,还有其他方法。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答