避免静态变量的解决方案

本文关键字:解决方案 变量 静态 | 更新日期: 2023-09-27 18:22:34

在我的解决方案中,我有一个带有Copy()Object Class,该将XElement从一个XML文件复制到另一个文件。

现在,我递归调用Copy(),因为我需要发送当前XElement内的Objects。在此过程中,我提取将要更新的特定attributevalue

现在,我发现执行此操作的唯一方法是提取所有这些值并将它们存储在每次生成Object的新实例时都不会更改的static variable中。

所以,基本上我有:

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的最佳方法是什么?

谢谢

避免静态变量的解决方案

一种解决方案是使该方法不是递归的,而是迭代的。 您可以编写一个通用树遍历方法来遍历 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());

重载 Copy 方法以接受列表作为参数。

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