我正在编写一个应用程序,我想确保在常量和文字方面有一个很好的编码标准。问题是,我不完全确定应该在哪里使用常量,以及使用常量只是过分了!例如......
(function(){
'use strict';
angular
.module('app')
.constant('config1', config1)
.constant('config2',
(function(){
return {
VERSION: 2
}
}())
);
function config1() {
return {
VERSION: '1'
}
};
})();
所以我的问题是,决定什么应该被宣布为常数,什么不应该是最广泛接受的标准是什么?我猜测在一个地方使用的任何东西只应该是文字(例如窗口的标题),而且几次使用的任何东西都应该是一个常量?
答案 0 :(得分:2)
const
字段存储在程序集metatada中。在某些其他程序集中引用程序集时,const
字段'VALUES将直接复制到引用程序集中。
因此,如果您决定更改const
字段,则必须重新编译引用它的所有程序集以查看更改。
例如,如果在Assembly1中你有:
public class Class1
{
public const string ConstString = "Const";
}
在Assembly2中引用它:
class Class2
{
void DoSomething()
{
Console.WriteLine(Class1.ConstString);
}
}
Class1.ConstString
将在编译时替换为常量("Const"
)的值。
答案 1 :(得分:0)
Constants are meant to denote constant variables and help the compiler to make optimizations and help the programmer to not change stuff that isn't meant to be changed.
Since there are no widely used specifications on this topic it's up to you how perfect you want to write your code and the size of your project. I'd say that the best practice would be to use const
whereever possible. It normally doesn't happen that often anyway to really become a problem and programming-style-wise it's good practice for nice and good coding.