为什么 Visual Studio 在使用“评论选择”评论多行选择时诉诸单行评论?

Sar*_*gis 4 .net c# comments visual-studio

关于Visual Studio 中的注释选择选项,我一直想知道的一些小事(Ctrl+ KCtrl+ C)。

当我评论这个方法的实现时,使用单行注释格式。

private void Foo()
{
    //Bar b = new Bar();
}
Run Code Online (Sandbox Code Playgroud)

当我在这里(部分行)对构造函数的参数进行注释时,使用了分隔注释格式。

private void Foo(Qux q)
{
    Bar b = new Bar(/*q*/);
}
Run Code Online (Sandbox Code Playgroud)

注释掉整个方法会导致:

//private void Foo()
//{
//    Bar b = new Bar();
//}
Run Code Online (Sandbox Code Playgroud)

我觉得分隔注释格式在最后一种情况下更合适,因为规范说:

单行注释延伸到源代码行的末尾。分隔注释可能跨越多行。

有谁知道为什么在 Visual Studio 中评论多行选择时将其选为默认格式?

Chr*_*air 6

这样做会有几个问题:


如果任何代码行中有一个*/位于其中,它将不起作用:

private void Foo(Qux q)
{
    //we use "*/image/*" flag here to find only images
    Bar b = new Bar("Some wildcard: */image/*");
}
Run Code Online (Sandbox Code Playgroud)

评论到:

/*
private void Foo(Qux q)
{
    //we use "*/image/*" flag here to find only images
    Bar b = new Bar("Some wildcard: */image/*");
}
*/
Run Code Online (Sandbox Code Playgroud)

如果您在已经包含分隔注释的部分点击“注释选择”,那么尝试用分隔注释包装代码将不起作用:

/*
private void Foo(Qux q)
{
    /* Some multiline 
     * comment
     */
    Bar b = new Bar();
}
*/
Run Code Online (Sandbox Code Playgroud)

但是很好,我们可以通过插入多个分隔注释和单行注释的组合来解决这个问题:

/*
private void Foo(Qux q)
{
    /* Some multiline 
     * comment
*/
//   */
/*
    Bar b = new Bar();
}
*/
Run Code Online (Sandbox Code Playgroud)

有点丑,但它有效。如果您遇到了注释代码,您是否能够立即识别出代码部分是什么以及注释部分是什么?此外,如果你点击“取消注释选择”命令,你会知道你会得到什么吗?

更进一步,想象一下如果你评论这条评论,它会变得更丑陋,更难以阅读。


如果您*/在文本中注释掉,则解决方法/转义注释会变得更糟(在我看来):

private void Foo(Qux q)
{
    //we use "*/image/*" flag here to find only images
    Bar b = new Bar("Some wildcard: */image/*");
}
Run Code Online (Sandbox Code Playgroud)

转换为:

/*
private void Foo(Qux q)
{
    //we use "**//*/image/*" flag here to find only images
    Bar b = new Bar("Some wildcard: **//*/image/*");
}
/*
Run Code Online (Sandbox Code Playgroud)

将上述令人困惑的注释代码与现有的单行实现进行比较:

//private void Foo(Qux q)
//{
//    /* Some multiline 
//     * comment
//     */
//    Bar b = new Bar();
//}

//private void Foo(Qux q)
//{
//    //we use "*/image/*" flag here to find only images
//    Bar b = new Bar("Some wildcard: */image/*");
//}
Run Code Online (Sandbox Code Playgroud)

这样做的好处是代码几乎是 1:1 的,就像以前一样,只是以//字符为前缀。如果您进一步评论或取消评论它,它仍然完全可读并且仍然完全可以预测它会是什么样子。嵌套的单行注释或嵌套的分隔注释没有任何问题。


也许最后,从 IDE 的角度来看,实现它真的非常简单:“注释选择”意味着//为每一行添加一个前缀,“取消注释选择”意味着删除前面的//. 不要纠结解析代码/注释,或解析不正确的语法代码/注释。