在 C# 的局部作用域中声明常量有什么好处吗?
如果我知道我不会改变局部变量的值,将其声明为“const”有什么好处吗?
谢谢,
Is there any benefit to declare a local variable as "const" if I know that I won't be chaning its value?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您通常会在整个解决方案中使用 const。但在本地范围内使用的好处是,您知道范围内的其他地方您不会更改它。而且,如果其他人正在编写此代码,他们也会知道不要更改它。
这使您的程序更易于维护,因为您只需要维护 const (即使它只是在本地范围内)
You would usually use a const throughout your entire solution. But the benefits for using in a local scope, would be that you know some place else in your scope you won't be changing it. And also if someone else is working on this code, they will know not to change it as well.
This makes your program more maintainable, because you need to maintain only the const (even if its just in a local scope)
声明变量 const 还允许编译器进行优化 - 编译器可能只是直接在代码中使用该值,而不是在堆栈上分配 int 并将其值放在那里,
即以下内容:
编译
可以由编译器
编辑:回复“constant propagation”,因为评论框有大小限制
使用ildasm检查const和none const之间的优化发布:
代码
编译为
While
得到优化为
This is using 2010 in release并进行优化。
我进行了搜索以了解有关常量传播的更多信息,虽然可能,但当前的编译器不会像提到的那样执行此操作 这里
Declaring the variable const will also allow the compiler to do optimisation - instead of say allocating an int on the stack and placing its value there, the compiler may just use the value directly with your code
ie The following:
Could be compiled as
by the compiler
Edit: Reply to "constant propagation" as the comments box has size limit
Using ildasm to check betweeen const and none const for release with optimisation:
The code
Compiles to
While
gets optimised to
This is using 2010 in release with optimisations.
I did a search to learn more about constant propagation and while posible, the current compiler doesn't do this as mentioned here
是的。您将保护您的代码免遭意外更改此变量。
Yes. You will protect your code from accidentally changing this variable.
当我将布尔标志指示器传递给方法时,我喜欢这样做:
这对我来说比简单的真/假更具可读性,后者需要读取方法声明来确定含义。
I like to do this when I'm passing a boolean flag indicator to a method:
This is more readable for me than a simple true/false, which requires reading the method declaration to determine the meaning.
将 local 声明为 const 将使编译器知道您的意图,因此您将无法在函数中的其他位置更改变量的值。
Declaring the local as const will let the compiler know you intention so you won't be able to change the value of your variable elsewhere in your function.
除了有效答案之外,您不仅告诉编译器该值不会更改,而且还可以快速告诉其他将查看您的代码的人。
Further to the valid answers, not only do you tell the compiler that the value won't be changing, you quickly tell anyone else that will be looking at your code.
取决于使用情况..
例如,
在这种情况下我认为 const 声明是没有意义的
Depending on case of use..
For example,
in this case I think const declaration is meaningless