2014-01-07 124 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」輕鬆獲得。 –