[英]Getter and Setter c#
我有多個對象(節點),每個節點都有一個名為Calea的列表的getter和setter方法,該列表包含其他節點,每個節點都有鄰居,並且它們也是node。 問題是列表在堆積,我不知道為什么,它就像一個靜態變量,而且我不在其他任何地方使用該getter和setter。 這是我的代碼:
private int cost = 10000;
private LinkedList<GraphNode<string>> calea=new LinkedList<GraphNode<string>>() ;
public int Cost
{
get
{
return cost;
}
set
{
cost = value;
}
}
public LinkedList<GraphNode<string>> Calea
{
get
{
if (calea == null) return new LinkedList<GraphNode<string>>();
return calea;
}
set
{
calea = value;
}
}
上面的代碼顯示了Cost和Calea的方法,Cost可以正常工作,但是Calea正在堆疊。下面的代碼是我如何為每個節點設置值Calea的代碼示例:
if (curr.Neighbors.ElementAt(i).Cost > curr.Costs.ElementAt(i) + curr.Cost)
{
curr.Neighbors.ElementAt(i).Cost = curr.Costs.ElementAt(i) + curr.Cost;
curr.Neighbors.ElementAt(i).Calea = curr.Calea;
curr.Neighbors.ElementAt(i).Calea.AddLast((GraphNode<string>)curr.Neighbors.ElementAt(i));
index = i;
}
++i;
我在下面更改當前節點的示例代碼:
pathNodesToVisit.Remove(curr);
if (pathNodesToVisit.Count == 0) break;
if (curr.Neighbors.Count > index)
{
for (int j = 0; j < pathNodesToVisit.Count; j++)
{
if (pathNodesToVisit.ElementAt(j).Value == curr.Neighbors.ElementAt(index).Value)
{
indexx = j;
//MessageBox.Show(pathNodesToVisit.ElementAt(j).Value);
}
}
curr = pathNodesToVisit.ElementAt(indexx);
}
else
{
curr = pathNodesToVisit.ElementAt(0);
}
幾句話:pathNodesToVisit是我要訪問的所有點頭(Dijkstra算法),在上面的代碼中,我從列表中刪除了curr節點,而新的curr節點是更改了Costs和Calea的節點。
我不知道您所說的“堆積”是什么意思,但是:
public LinkedList<GraphNode<string>> Calea
{
get
{
if (calea == null) return new LinkedList<GraphNode<string>>();
return calea;
}
... 每次讀取屬性時都會創建一個新列表,而不僅僅是第一次。 使用這種方法, calea
將始終為null
。
嘗試
get
{
if (null == calea)
calea = new LinkedList<GraphNode<string>>();
return calea;
}
更新資料
線
curr.Neighbors.ElementAt(i).Calea = curr.Calea;
不復制列表。 它將引用復制到列表。 之后,對任何節點的calea
進行的任何更改都會影響每個節點,而不僅僅是您所追求的節點。
嘗試
curr.Neighbors.ElementAt(i).Calea = new LinkedList<GraphNode<string>>(curr.Calea);
但是,您應該確保.Neighbors
實際上在執行此操作之前還有一個i
元素。
注意:對於未初始化的節點,這實際上將創建兩個列表-一次在讀取Calea時(表達式的LH,調用.get
),另一個在右側。
復制集合有很多方法。 我建議使用谷歌搜索c# deep copy LinkedList<T>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.