我是 OO 设计的新手,我想知道在设计中对象包含其他对象的列表是否很典型。示例如下:
// Person object containing a list of phone numbers
public class Person
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Phone> Contacts { get; set; }
public void AddPhoneNumber(Phone phone)
{
Contacts.Add(phoneNumber);
}
}
// Phone object
public class Phone
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
}
// Example code to establish an object:
Person p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Smith";
p1.AddPhoneNumber(new Phone() { Number = "555957000" });
p1.AddPhoneNumber(new Phone() { Number = "555579561" });
是否有更好的方法来构建它以简化设计并允许更轻松地访问数据?谢谢!
最佳答案
是的,让一个对象包含对象列表绝对没问题。在 OOPs
中,这称为 Composition,它表示参与的 class
之间的强关系。
关于c# - 对象中有对象列表是正常的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43148971/