C# 代码中的行内注释会影响编译的 dll 吗?

Do in-line comments in C# code affect the compiled dll?

考虑一个内容非常少的 C# 文件,例如

...
public void DoSomething()
{
    Console.WriteLine("Does Something!");
}
...

同样的片段中有评论:

...
public void DoSomething()
{
    // This line does something!
    Console.WriteLine("Does Something!");
}
...

当编译器将此文件放入 dll 中时,它将删除多余的部分并使其成为机器可读的。这是否意味着两个 dll 完全相同?这两个文件显然有不同的行数,并且会散列为不同的值,但编译器会关心吗?空行是否会产生与更改文件相同的影响,例如

...
public void DoSomething()
{

    Console.WriteLine("Does Something!");
}
...

我使用 SharpLab 为您检查了这一点(尽管我已经知道注释不会影响生成的 IL)。

public void Main()
{
    // Useful comment
    Console.WriteLine("Hello world!");
}

public void Main()
{
    /* Useful comment */ Console.WriteLine("Hello world!");
}

都编译为

public void Main()
{
    Console.WriteLine("Hello world!");
}

这是因为编译器通常会忽略注释,除非它们是文档注释或者您正在生成需要行号才能正常工作的调试符号。

Does this mean that both dll's are entirely identical?

也许吧。这里有一点微妙之处。

  • 默认情况下,C# 编译器不是确定性的。也就是说,即使使用完全相同的输入,由于生成的 ID,您也可能获得不同的 DLL。我知道有人推动确定性模式成为 .NET Core SDK 项目的默认模式,但我不确定这是否发生了。在命令行中,只需 运行 csc with Roslyn 2.8.0.62830,deterministic 而不是 默认值
  • 行号通常不影响 IL,但它们会影响正在生成的任何 PDB 文件,以便调试器知道源代码中的哪一行对应于什么 IL。即使行号没有变化,PDB 文件也包含源代码的散列,以便调试器可以检查它是否正在查看 "right" 代码。
  • 行号可以由于调用者信息属性无论如何都会有影响,如下代码所示:

    using System;
    using System.Runtime.CompilerServices;
    
    class Program
    {
        public static void Main()        
        {
            // Remove this comment and get a different result
            PrintLine();
        }
    
        static void PrintLine([CallerLineNumber] int line = 0)
        {
            Console.WriteLine(line);
        }
    }
    

有注释,打印 9。没有注释,打印 8。IL 不同,因为行号作为常量嵌入其中。

如果您担心评论会影响性能,您绝对不应该这样做。但是,如果您真的担心 任何 改变是否可能仅通过进行通常不会影响行为的改变 - 是的,可能会有细微的改变。