而不是写出
var parentContainer0 = this.Parent;
var parentContainer1 = parentContainer0.Parent;
var parentContainer2 = parentContainer1.Parent;
有没有更好的方法来列出父容器的所有层?
答案 0 :(得分:2)
要获取所有祖先的序列,您可以编写一个迭代器块来轻松计算它:
public static IEnumerable<Control> GetAncestors (Control control)
{
var current = control.Parent;
while (current != null)
{
yield return current;
current = current.Parent;
}
}
如果你想要第N代父代,你可以在这个序列上使用ElementAt
,使用LINQ:
var grandparent = someControl.ElementAt(2);
答案 1 :(得分:1)
List<Control> layers = new List<Control>();
Control currentLayer = this.Parent;
while (currentLayer != null)
{
layers.Add(currentLayer);
currentLayer = currentLayer.Parent;
}