C# 递归和变量值

C# 递归和变量值,c#,.net,recursion,C#,.net,Recursion,我有一个递归方法,简化如下: private List<string> data; public string Method1() { data = new List<string>(); //When Method 1 gets called first time there is a problem //When Method 1 gets called from Method2 problem is fixed if (proble

我有一个递归方法,简化如下:

private List<string> data;
public string Method1()
{
    data = new List<string>();

    //When Method 1 gets called first time there is a problem
    //When Method 1 gets called from Method2 problem is fixed
    if (problem)
    {
        data.Add("prob");
    }

    if(data.Count > 0)
    {
        return Method2()
    }
    else
    {
        return string.Empty();
    }
}

private string Method2()
{
    return Method1();
}
私有列表数据;
公共字符串Method1()
{
数据=新列表();
//第一次调用方法1时出现问题
//当从Method2调用方法1时,问题已修复
如果(问题)
{
数据。添加(“prob”);
}
如果(data.Count>0)
{
返回方法2()
}
其他的
{
返回字符串.Empty();
}
}
私有字符串方法2()
{
返回方法1();
}

当Method1从Method2调用时,我是否正确地认为,
数据
变量被重新初始化,清除了以前在那里的内容?

当调用
方法1时,您正在创建新的
列表
因此旧的
数据
变量值变得不可访问(将被垃圾收集)


为了避免这种情况,您必须在
方法1
之外的某个地方初始化
数据
,例如在构造函数中。

这样认为。有一个奇怪的错误,当Method1从Method2调用时,它仍然说有问题,并怀疑这是否是因为列表中最初有数据,但我确信递归会消除它。