在遞回函式中,我將元素附加到一個串列(IEnumerable),我將其作為引數提供給函式。
像這樣的東西:
public class FooObject {
private string Name;
private List<FooObject>? Childs;
public void RecursiveFunction(IEnumerable<FooObject> excludeList) {
if (!excludeList.Any(x => x.Name == this.Name))
return;
excludeList = excludeList.Append(this);
foreach (var child in this.Childs) {
child.RecursiveFunction(excludeList);
}
}
}
問題是,例如在深度 3 中,它將一個元素附加到串列中并且沒有子元素,因此完成并再次上升到深度 2,并且深度 3 中的附加元素不再在串列中。
這種行為是有意的還是我誤解了函式引數和指標的概念?
uj5u.com熱心網友回復:
您為變數分配了一個不同的可列舉excludeList,類似于:
var excludeList = originalList;
excludeList = otherList; // now originalList is not changed, of course
您需要讓方法獲取真實串列并使用它的Add方法
public void RecursiveFunction(List<FooObject> excludeList) {
if (excludeList.Any(x => x.Name == this.Name))
return;
excludeList.Add(this);
foreach (var child in this.Childs) {
child.RecursiveFunction(excludeList);
}
}
如果你想支持更多的收藏,List<T>你可以允許ICollection<T>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437687.html
標籤:C#
上一篇:我可以在catch陳述句中添加什么來顯示導致錯誤的屬性?
下一篇:記錄不輸出任何東西
