C# 我应该尽可能使用常量字符串而不是字符串吗?
考虑以下三个例子: 例AC# 我应该尽可能使用常量字符串而不是字符串吗?,c#,.net,optimization,il,C#,.net,Optimization,Il,考虑以下三个例子: 例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!"); 有什么理由用一个来代替其他的吗?具体来说,我是否应该在可能的情况下尝试使用c
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!");
有什么理由用一个来代替其他的吗?具体来说,我是否应该在可能的情况下尝试使用conststring(假设字符串从未被修改),因此示例B是最好的?在示例C中发生了什么
我想我是在问,上面所说的IL是相同的还是不同的,是否有任何不同。我认识到差别很小,可能没有什么可担心的;我想这是一个学术问题
编辑这是IL
看起来和我完全一样。真的取决于上下文。这个信息会改变吗?如果您使用选项A,您就有机会修改字符串消息的值,而另外两个选项则打印一个硬编码字符串-如果它总是说性能、内存使用或字符串表效率没有差异,那么这很好
const关键字的唯一作用是在重新分配字符串时生成编译时错误。因此,添加const有助于将您的意图传达给其他开发人员 带上反编译器去镇上!我不明白你为什么不看看IL然后自己决定?有了正确的编译器选项,它们实际上应该是一样的。问题是一个不切实际的苹果和橘子的比较。B只能是一个字段。可以是字段或局部变量。C只能内联声明。您可以在方法中声明B,但我通常只将其用作字段。
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