首页 > 解决方案 > 具有 x 个附加对象的类

问题描述

假设我有一个带有构造函数的名为 Person 的类

public class Person
{
     public string Name { get; set;}
     public string Height { get; set; }
     public string WhatEverElse { get; set; }

     public string Person(string Name, string Height, string WhatEverElse)
     {
          this.Name = Name;
          .......
     }
}

现在假设我还想包括一个人可能拥有的所有宠物。

List<Person> persons = new List<Person>();

persons.Add(new Person("Larry", "5'9", "Whatever"));

foreach(Datarow row in OwnedPets)
{
     //push the pet info to the person here
}

有没有办法可以将 x 数量的宠物和宠物信息添加到 Person 对象?这样我就可以带回拉里和他的所有 2 只宠物或杰里和他的所有 6 只宠物?或者我可以结合两个类并返回一个列表吗?

标签: c#classobject

解决方案


清单怎么样?


public class Person
{
     public string Name { get; set;}
     public string Height { get; set; }
     public string WhatEverElse { get; set; }
     public List<Pet> Pets { get; set; }
     public string Person(string Name, string Height, string WhatEverElse)
     {
          Pets = new List<Pet>();
     }
}

public class Pet
{
     public string Name { get; set; }
}

然后,您可以通过分配新宠物来添加任意数量的宠物

// For your own sake keep a clear naming convention - just my two bucks
List<Person> persons = new List<Person>();
Person person = new Person("Larry", "5'9", "Whatever");
persons.Add(person);

foreach(Datarow row in OwnedPets)
{
     Pet newPet = new Pet();
     person.Pets.Add(newPet);
}

推荐阅读