2

考虑这三个例子:

示例 A

string message = "Hello world!";
throw new System.Exception(message);

示例 B

const string message = "Hello world!";
throw new System.Exception(message);

示例 C

throw new System.Exception("Hello world!");

有什么理由使用其中一个而不是其他?具体来说,我不应该在可能的情况下尝试使用 const 字符串(假设字符串从未被修改过),因此示例 B 是最好的吗?示例 C 中发生了什么?

我想我是在问上面发出的 IL 是相同还是不同,是否有任何区别。我认识到差异会很小,可能没有什么可担心的;我想这使这是一个学术问题。


编辑。这是IL

IL_0014: ldstr "This is a string"
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0020: throw


IL_0033: nop
IL_0034: ldstr "This is a const string"
IL_0039: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_003e: throw

IL_0051: nop
IL_0052: ldstr "This is an inline string."
IL_0057: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_005c: throw

看起来和我基本一样。

4

2 回答 2

1

取决于上下文,真的。这个信息会改变吗?如果您使用选项 A,您有机会修改字符串消息的值,而另外两个您正在打印一个硬编码字符串 - 这很好,如果它总是这么说的话

于 2013-11-07T20:47:53.683 回答
0

在性能、内存使用或字符串表效率方面没有区别。

const 关键字的唯一作用是在重新分配字符串时生成编译时错误。因此,添加 const 有助于将您的意图传达给其他开发人员。

于 2013-11-12T22:30:56.217 回答