2014-09-18 70 views
0

在我的解決方案中,我有一個Object Class和一個Copy(),它將XElement從一個XML文件複製到另一個。避免靜態變量的解決方案

現在,我遞歸地呼叫Copy(),因爲我需要發送Objects,這是目前的XElement。在此過程中,我提取將更新的特定attributevalue

現在,我發現這樣做的唯一辦法,就是抽取所有這些值並將其存儲在一個static variable不會所生成的Object的新實例每次被改變。

所以,基本上我有:

public class Item 
{ 
    public XElement Element; 

    private static readonly List<Tuple<string, string>> Ids = new List<Tuple<string, string>>(); 

    public String Copy(){ 

     //Recursively get all the OldIds from the current Element 

     //populate the List with oldIds and "" 

     //generate newId for this 

     //update List that matches the OldId and put the newId 

     //Update the Element 

     //Transfer Element 

     return newId;  
    } 
} 

什麼是避免使用static List的最佳方式?

謝謝

+1

稱它是**全球**變量可能會引起誤解。在C++中,全局變量不存在於類中,並且在C#中不允許全局變量。您可能想將其稱爲**靜態**變量,以便清楚。 – 2014-09-18 18:35:49

回答

2

一個解決方案是使該方法不是遞歸的,而是迭代的。您可以編寫通用樹遍歷方法來遍歷XML樹,然後在您擁有的元素上調用它,從而允許您填充列表,而無需在方法調用之間共享任何狀態。

這裏是遍歷樹一個簡單的方法:

public static IEnumerable<T> Traverse<T>(
    this IEnumerable<T> source 
    , Func<T, IEnumerable<T>> childrenSelector) 
{ 
    var stack = new Stack<T>(source); 
    while (stack.Any()) 
    { 
     var next = stack.Pop(); 
     yield return next; 
     foreach (var child in childrenSelector(next)) 
      stack.Push(child); 
    } 
} 

然後,您可以打電話給你的元素上的方法來獲取子元素的全樹:

XElement element = GetElement(); 
var tree = new[] { element }.Traverse(e => e.Elements()); 
+0

聽起來不錯。但是,最後我還想轉移這些項目。這就是爲什麼我再次爲他們打電話複製。 – 2014-09-18 18:59:37

+0

@LuisLavieri然後在一個循環中傳遞所有的項目,而不是使用遞歸。一個簡單的'foreach'可以讓你爲每個項目執行代碼。 – Servy 2014-09-18 19:01:40

+0

是的。我想這樣:)謝謝 – 2014-09-18 19:04:26

1

重載Copy方法以接受列表作爲參數。

public String Copy(List<Tuple<string, string>> Ids) {} 

public String Copy() {} 
+0

超過重載,我認爲可選參數。謝謝 – 2014-09-18 19:06:00