坚持function和布尔

我有一个名为firstRun()函数,在其中我有两个已定义的filesDeleteddirsDeleted

同样在函数里面我有if (filesDeleted == true && dirsDeleted == true) {
当我尝试调试应用程序时,我得到错误 – Use of unassigned local variable 'filesDeleted'Use of unassigned local variable 'dirsDeleted'尝试了很多不同的解决方案,根本不起作用。

这是代码:

 private void firstRun(bool forceDelete) { string Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "myLauncher"); string[] Files = Directory.GetFiles(Path); string[] Dirs = Directory.GetDirectories(Path); bool filesDeleted; bool dirsDeleted; if (forceDelete == true) { if (Directory.Exists(Path)) { string lastFile = Files[Files.Length - 1]; foreach (string file in Files) { if (file == lastFile) { filesDeleted = true; MessageBox.Show("test"); } File.Delete(file); } string lastDir = Dirs[Dirs.Length - 1]; foreach (string dir in Dirs) { if (dir == lastDir) { dirsDeleted = true; MessageBox.Show("test2"); } Directory.Delete(dir, true); } if (filesDeleted == true && dirsDeleted == true) { //code when everything deleted } } else { Directory.CreateDirectory(Path); } } 

改变你的

 bool filesDeleted; bool dirsDeleted; 

 bool filesDeleted = false; bool dirsDeleted = false; 

这些是局部变量, 必须在使用它们之前进行分配。

5.1.7 Local variables

局部变量不会自动初始化,因此没有默认值 。 出于明确赋值检查的目的,最初认为局部变量未分配。

与类成员变量不同,方法中的局部变量没有默认值,在尝试读取它们之前必须明确赋值:

所以你需要使用

 bool fileDeleted = false; bool dirsDeleted = false; 

代替

 bool filesDeleted; bool dirsDeleted;