在此scnario中,程序将xmlfiles放在目录中.如果已经在listToWatch列表中添加了xmlfile,则会在第二种方法中对其进行评估.但是,firstMethod也会循环用于评估每个目录(下面没有写入).
该程序检测已添加的xml文件中的所有文件.但是如果程序进入另一个目录(因为firstMethod在另一个类中循环),则传递listToWatch = new List(),删除先前的listToWatch并创建一个新对象.
我希望使用相同的对象而不会被新列表覆盖.我不能把listToWatch =新名单secondMethod因为有一个for循环,系统将仅覆盖listToWatch一个新的对象.我不能把它放在firstMethod中,因为它需要在secondMethod中设置.我也不能把它放在类Sample中.我应该把listToWatch = new List()放在哪里?
class Sample
{
public static List<string> listToWatch
{
get;
set;
}
public static void firstMethod()
{
string getFiles = Directory.GetFiles(directory, "*.xml");
foreach (string xmlFile in getFiles)
{
secondMethod(xmlFile);
}
}
public static void secondMethod(xmlFile)
{
listToWatch = new List<string>();
foreach (string file in xmlFile)
{
if (listToWatch.Contains(file))
{
sw.WriteLine(file + " is already added!");
}
else
{
listToWatch.add();
}
}
}
Run Code Online (Sandbox Code Playgroud)
用getter和setter怎么样?
private static List<string> _ListToWatch;
public static List<string> ListToWatch
{
get
{
if(_ListToWatch == null)
_ListToWatch = new List();
return _ListToWatch;
}
set
{
_ListToWatch = value;
}
}
Run Code Online (Sandbox Code Playgroud)
必须说,可能是更好的选择让方法返回此对象而不是存储它,但如果由于某种原因你不能改变它,我认为这将工作
编辑:感谢@gorpik,这被称为" 属性 "而不是" 使用getter和setter ".