【发布时间】:2014-04-24 20:28:35
【问题描述】:
有没有办法将编译时常量的范围限制为避免硬编码值的方法/代码块?
类似于以下内容:
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;
}
}
【问题讨论】:
-
你为什么要那个?
return a + 10有什么问题? -
是什么让你认为“显然它不存在?”
-
// obviously this doesn't exist我很确定它完全可以 -
@Selman22 想象在您的方法/块中多次使用该值。如果你需要改变某些东西,你不会想改变它的每一次使用。
-
以上cmets都对,请问之前有试过吗?如果你没有,你应该