它们是堆栈上的不可变值类型.什么阻止我让他们成为一个常量?
参考文献:
[TestClass]
public class MsProjectIntegration {
const int? projectID = null;
// The type 'int?' cannot be declared const
// ...
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能拥有const int??
编辑:我想要一个可空的int作为const的原因是因为我只是用它来从数据库加载一些示例数据.如果它为null我只是在运行时初始化样本数据.这是一个非常快速的测试项目,显然我可以使用0或-1,但int?感觉就像我想做的那样正确的数据结构.readonly似乎是要走的路
如何将Color类型声明为const:
private const Color MyLovedColor = Color.Blue;
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为Color.Blue是静态而不是const.
(readonly不会帮助我,因为我需要一个"仅支持"常量的属性的颜色