C# 注释不能放在括号内的语句中

C# 注释不能放在括号内的语句中,c#,coding-style,stylecop,C#,Coding Style,Stylecop,我在我的C#文件中使用StyleCop,它给出了警告: SA1108:CSharp.可读性:注释不能放在括号内的语句中 对于以下代码块: // checking if the person is born or not. if (AgeUtilities.IsPersonBorn(person.BirthDate) == false) { Console.WriteLine("Error....The user is not yet born."); } // checking if

我在我的C#文件中使用StyleCop,它给出了警告:

SA1108:CSharp.可读性:注释不能放在括号内的语句中

对于以下代码块:

// checking if the person is born or not.
if (AgeUtilities.IsPersonBorn(person.BirthDate) == false)
{
    Console.WriteLine("Error....The user is not yet born.");
}

// checking if the person's age is possible or not.
else if (AgeUtilities.IsPersonLongAgePossible(age, EXPECTEDAGELIMIT) == false)
{
    Console.WriteLine("This age is not possible in Today's world.");
}

此警告的意义是什么?

StyleCop告诉您应该在括号内的else语句上方替换/重新组织您的注释,如

    // checking if the person is born or not
    // if not: check if the person's age is possible or not
    if (AgeUtilities.IsPersonBorn(person.BirthDate) == false)
    {
        Console.WriteLine("Error....The user is not yet born.");
    }
    else if (AgeUtilities.IsPersonLongAgePossible(age, EXPECTEDAGELIMIT) == false)
    {
        Console.WriteLine("This age is not possible in Today's world.");
    }

请看一看。

我不使用StyleCop,但在我看来,因为您在
if/elseif
之间添加了空格,所以您可能会遇到潜在的错误,因为其他开发人员可能不会注意到
else if
,因为此代码在此基础上展开并包含另一条
if
语句,这样就破坏了你的程序。我个人认为,既然您已经给出了非常自解释的方法名称,您就不需要注释了here@Sayse即使删除了空行,同样的警告也会出现。在这种情况下,您也应该将注释视为空行。我的观点是,很容易看出
elseif
属于
if
语句,如果可以看到它上面的括号(或者如果没有括号,则在它上面两行的if语句),则不要在代码中使用不必要的注释,例如在这种情况下:代码本身是完全可以理解的。注释是多余的,只会引入噪声,这会降低代码的可读性。此外,每当您或其他人更改这段代码中的某些内容时,您也必须更改注释(有人会忘记这样做,使代码/注释不连贯)。如果有多个具有复杂条件的“else-If”语句,那么这样的注释是最好的方法吗?当然不是——当我面对多个else if语句时,我更喜欢做的是,我提取语句本身(比如AgeUtilities.isPersonBorn(person.BirthDate)==false),并将其放入一个函数中,该函数返回一个布尔值并将其称为PersonIsBorn()。这种方法可以减少注释和提高可读性,而且测试代码也会变得更容易,因为您可以通过模拟/存根“简单”地访问方法及其返回值。