可能是错误的空声明警告

时间:2014-01-07 01:06:26

标签: c#

编译此代码时,我收到一条“可能错误的空语句”警告:

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();
        }
    }
}

我试图解决它,但我做不到。这个警告意味着什么,问题出在哪里?

1 个答案:

答案 0 :(得分:9)

一个“可能错误的空语句”警告意味着你的代码中有一个声明,应该是复合的(即包含一个像这样的“身体”:statement { ... more statement ... }),而不是身体有一个分号{{ 1}}终止语句。您应该立即知道错误的地方和位置,只需双击导航到相应代码行的警告即可。

像这样的常见错误如下:

;

具体来说,在本声明的代码中:

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 ,可能?)。