作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我有一个像下面这样的类。我如何遍历它直到它的属性 SomeObjects.count = 0
public class SomeObject
{
public String Name { get; set; }
public List<SomeObject> SomeObjects { get; set; }
}
非常感谢
最佳答案
这是一个关于如何遍历复合对象的通用示例:
public static class TraversalHelper{
public static void TraverseAndExecute<T>(this T composite, Func<T,IEnumerable<T>> selectChildren, Action<T> action)
where T: class
{
action.Invoke(composite);
composite.TraverseAndExecute(selectChildren, action, new List<T>{ composite });
}
private static void TraverseAndExecute<T>(this T composite, Func<T,IEnumerable<T>> selectChildren, Action<T> action, IList<T> invokedComponents)
where T: class
{
invokedComponents = invokedComponents ?? new List<T>();
var components = selectChildren(composite) ?? new T[]{};
foreach(var component in components){
// To avoid an infinite loop in the case of circular references, ensure
// that you don't loop over an object that has already been traversed
if(!invokedComponents.Contains(component)){
action.Invoke(component);
invokedComponents.Add(component);
component.TraverseAndExecute<T>(selectChildren, action, invokedComponents);
}
else{
// the code to execute in the event of a circular reference
// would go here
}
}
}
}
这是一个示例用法:
public class Program{
public static void Main(){
var someObject = new SomeObject {
Name = "Composite",
SomeObjects = new List<SomeObject>{
new SomeObject{ Name = "Leaf 1" },
new SomeObject{
Name = "Nested Composite",
SomeObjects = new List<SomeObject>{ new SomeObject{Name = "Deep Leaf" }}
}
}
};
someObject.TraverseAndExecute(
x => x.SomeObjects,
x => { Console.WriteLine("Name: " + x.Name); }
);
}
}
关于c# - 遍历层次对象c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6501096/
我是一名优秀的程序员,十分优秀!