【问题标题】:property within a class with the same properties as the parent class [closed]与父类具有相同属性的类中的属性[关闭]
【发布时间】:2016-08-09 03:49:38
【问题描述】:

我有以下班级,我需要它在父班级中有一个孩子和孩子的孩子。 我该怎么做?

public class Person  {
public string Name { get; set; }
public int Age { get; set; }
// this person can have one or more children with Name & age properties
//this person's children can have one or more children with Name & age properties
}  

谢谢

【问题讨论】:

  • public List<Person> Children { get; } = new List<Person>(); 更一般地说,这是一种recursive data type
  • public List<Person> Children { get;set;}?
  • 某些监视器不让我回答您的问题。不要创建子项列表,因为每个子项将只有一个父项。每个人都应该有一个父母列表... List 父母。
  • @JasonWilliams 那么你将如何处理一个有多个孩子的父母?显然,这个父母需要出现在多个列表中,属于他们的每个孩子?如果您接受这是 possible in principle,那么为什么 Child 不能出现在多个列表中,每个 Parent 一个?
  • @JasonWilliams IMO,这完全取决于您的用例是什么。有了孩子的名单,就很难得到祖先的名单;有了父母的名单,就很难得到孩子或兄弟姐妹的名单。 (在这两种情况下,您都需要搜索所有人的全局列表)。 OP 确实没有提供足够的信息来了解什么是最好的模型。当然,无论使用哪种结构,都无法避免“无意义”的情况(例如周期性的父子关系)。你真的需要一个more sophisticated data structure

标签: c#


【解决方案1】:

它可以引用自己。

public class Person  {
    public string Name { get; set; }
    public int Age { get; set; }
    public List<Person> Children { get; set; }
}  

【讨论】:

  • 就个人而言,我更愿意将Children 设为只读并使用空列表对其进行初始化。这样你就不用担心检查person.Children == null
  • 不要创建子项列表,因为每个子项将只有一个父项。每个人都应该有一个父母列表... List Parents
  • 谢谢。这正是我所需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多