问题描述
每当我在方法中有局部变量时,ReSharper 都会建议将它们转换为常量:
Whenever I have local variables in a method, ReSharper suggests to convert them to constants:
// instead of this:
var s = "some string";
var flags = BindingFlags.Public | BindingFlags.Instance;
// ReSharper suggest to use this:
const string s = "some string";
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
鉴于这些确实是常量值(而不是变量),我理解 ReSharper 建议将它们更改为 const.
Given that these are really constant values (and not variables) I understand that ReSharper suggest to change them to const.
但除此之外,使用 const 时是否还有其他优势(例如更好的性能),这证明使用 const BindingFlags
而不是方便且可读的 var
关键字是合理的?
But apart from that, is there any other advantage when using const (e.g. better performance) which justifies using const BindingFlags
instead of the handy and readable var
keyword?
顺便说一句:我刚刚在这里发现了一个类似的问题:Resharper 总是建议我制作 const 字符串而不是字符串,但我认为这更多是关于类的字段,而我的问题是关于局部变量/consts.
BTW: I just found a similar question here: Resharper always suggesting me to make const string instead of string, but I think it is more about fields of a class where my question is about local variable/consts.
推荐答案
如果你试图给一个常量赋值,编译器会抛出一个错误,从而可能会阻止你不小心改变它.
The compiler will throw an error if you try to assign a value to a constant, thus possibly preventing you from accidentally changing it.
此外,使用常量与变量相比,通常会在性能上有所提升.这与将它们编译到 MSIL 的方式有关,根据 this MSDN 杂志 Q&A:
Also, usually there is a small performance benefit to using constants vs. variables. This has to do with the way they are compiled to the MSIL, per this MSDN magazine Q&A:
现在,在代码中引用 myInt 的任何地方,都不必执行ldloc.0".要从变量中获取值,MSIL 只需加载硬编码到 MSIL 中的常量值.因此,使用常量通常会在性能和内存方面带来较小的优势. 但是,要使用它们,您必须在编译时获得变量的值,以及在编译时对该常量的任何引用,即使它们在不同的程序集中,也会进行此替换.
Now, wherever myInt is referenced in the code, instead of having to do a "ldloc.0" to get the value from the variable, the MSIL just loads the constant value which is hardcoded into the MSIL. As such, there's usually a small performance and memory advantage to using constants. However, in order to use them you must have the value of the variable at compile time, and any references to this constant at compile time, even if they're in a different assembly, will have this substitution made.
如果您知道编译时的值,常量肯定是一个有用的工具.如果你不这样做,但想确保你的变量只设置一次,你可以使用 C# 中的 readonly 关键字(在 MSIL 中映射为 initonly)来指示变量的值只能在构造函数中设置;之后,更改它是错误的.这通常在字段有助于确定类的身份时使用,并且通常设置为等于构造函数参数.
Constants are certainly a useful tool if you know the value at compile time. If you don't, but want to ensure that your variable is set only once, you can use the readonly keyword in C# (which maps to initonly in MSIL) to indicate that the value of the variable can only be set in the constructor; after that, it's an error to change it. This is often used when a field helps to determine the identity of a class, and is often set equal to a constructor parameter.
这篇关于在方法中使用 const 而不是变量的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!