我有一个看起来像这样的区类:
public class District
{
public int Id { get; set; }
public string Name { get; set; }
public District Parent { get; set; }
public IEnumerable<District> Ancestors { get { /* what goes here? */ } }
}
Run Code Online (Sandbox Code Playgroud)
我希望能够得到每个区的祖先名单.因此,如果区"1.1.1"是区域"1.1"的子区域,这是区域"1"的子区域,则获得区域"1.1.1"上的祖先将返回包含名称为"1.1"的区域对象的列表. "和"1".
这是否涉及收益率报表(我从未完全理解)?可以一行完成吗?
Jon*_*eet 11
如果线路足够长,一切都可以在一行完成:)
在这种情况下,它可能最简单的不是在一行中完成:
public IEnumerable<District> Ancestors
{
get
{
District parent = Parent;
while (parent != null)
{
yield return parent;
parent = parent.Parent;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想yield return
更好地理解它只是一个简短的插件- 深度C#第一版的第6章仍然是免费提供的,而这一切都与C#2中的迭代器有关.从第一版页面中获取它.