2014-01-07 48 views
-3

我得到一个“可能错误的空语句”的警告,当我编译此代码:可能误以为空语句警告

class Lab6 
{ 
    static void Main(string[] args) 
    { 
     Program fileOperation = new Program(); 

     Console.WriteLine("Enter a name for the file:"); 
     string fileName = Console.ReadLine(); 

     if (File.Exists(fileName)) 
     { 
      Console.WriteLine("The file name exists. Do you want to continue appendng ? (Y/N)"); 
      string persmission = Console.ReadLine(); 

      if (persmission.Equals("Y") || persmission.Equals("y")) 
      { 
       fileOperation.appendFile(fileName); 
      } 
     } 
     else 
     { 

      using (StreamWriter sw = new StreamWriter(fileName)) ; 
      fileOperation.appendFile(fileName); 
     } 
    } 

    public void appendFile(String fileName) 
    { 
     Console.WriteLine("Please enter new content for the file - type Done and press enter to finish editing:"); 
     string newContent = Console.ReadLine(); 
     while (newContent != "Done") 
     { 
      File.AppendAllText(fileName, (newContent + Environment.NewLine)); 
      newContent = Console.ReadLine(); 
     } 
    } 
} 

我试图修复它,但我不能。这个警告是什么意思,问题在哪里?

+2

请在下一次问问题时加倍努力。看到我的编辑,我试图让它至少有一点可读性和可理解性。此外,标题“嗨,我是新的......”真的**不合格。标题**必须是您的问题的简短摘要。 –

+0

感谢您的评论。 “ – user3164058

+0

”问题在哪里?“ - 您忽略提供的错误消息包含错误的行号。你有一个'use'语句来设置'sw',但你从不使用'sw'。 –

回答

9

“可能是空的错误语句”警告意味着代码中有一个声明,应该是复合的(即包含一个“body”,例如:statement { ... more statement ... }),但是代替body的是分号;,它会终止声明。您应该立即知道哪里和哪里出了问题,只需双击导航到相应代码行的警告即可。

像这样常见的错误是这样的:

if (some condition) ; // mistakenly terminated 
    do_something(); // this is always executed 

if (some condition); // mistakenly terminated 
{ 
    // this is always executed 
    ... statement supposed to be the 'then' part, but in fact not ... 
} 

using (mySuperLock.AcquiredWriterLock()); // mistakenly terminated 
{ 
    ... no, no, no, this not going to be executed under a lock ... 
} 

具体来说,在你的代码在此声明:

using (StreamWriter sw = new StreamWriter(fileName)) ; 

有一个;底,使得using空(=没用)。紧随其后的代码行:

fileOperation.appendFile(fileName); 

无关任何StreamWriter任何,所以有明显东西代码中的缺失(或东西遗留 - 在using,大概?)。

+2

+1。有关[CS0642](http://msdn.microsoft.com/en-us/library/9x19t380%28v=vs.90%29.aspx)的MSDN信息可通过在VS中选择错误时单击“F1”轻松获得。 –