考虑以下三个例子:

示例

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

看起来与我完全相同。

有帮助吗?

解决方案 2

性能,内存使用或字符串表效率没有差异。

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

其他提示

实际上取决于上下文。这个消息会改变吗?如果使用选项A,则有机会修改字符串消息的值,而您正在打印硬编码字符串的其他两个字符串 - 很好,如果总是这样说

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top