有没有办法将编译时常量的范围限制为避免对值进行硬编码的方法/代码块?
如下所示:
public int SomeMethod(int a) {
const int SomeCompileTimeConstant = 10; // obviously this doesn't exist
return a + SomeCompileTimeConstant;
}
反对硬编码值:
public int SomeMethod(int a) {
return a + 10;
}
或使其成为类级常量:
public class A {
private const int SomeCompileTimeConstant = 10;
public int SomeMethod(int a) {
return a + SomeCompileTimeConstant;
}
}
答案 0 :(得分:3)
您可以在函数内声明一个常量。
当你写
时public int SomeMethod(int a) {
const int SomeCompileTimeConstant = 10; // obviously this doesn't exist
return a + SomeCompileTimeConstant;
}
你错了。