为什么不能nullables被声明为const? [英] Why can't nullables be declared const?
问题描述
[TestClass]
public class MsProjectIntegration {
const int? projectID = null;
// The type 'int?' cannot be declared const
// ...
}
为什么我不能有一个 const int的?
?
编辑:我想一个可空INT作为一个const的原因是因为我只是用它从数据库加载一些示例数据。如果是空,我只是要在运行时初始化样本数据。这是一个非常快速的测试项目,很明显,我可以用0或-1,但 INT?
只是觉得像我想要做正确的数据结构。只读似乎是要走的路。
The reason I wanted a nullable int as a const is because I'm just using it for loading some sample data from a database. If it's null I was just going to initialize sample data at runtime. It's a really quick test project and obviously I could use 0 or -1 but int?
just felt like the right data structure for what I wanted to do. readonly seems like the way to go
推荐答案
这不仅仅是nullables;仅内置于运行时类型可以声明常量
(从内存中,它的bool,各类整型,花车/双打和字符串)。
It's not just nullables; only types built into the runtime can be declared const
(from memory, it's bools, the various types of int, floats/doubles, and strings).
为什么呢?因为该值被直接嵌入到在编译时组装,而且也没有办法嵌入用户定义类型。
Why? Because the value gets embedded directly into the assembly at compile time, and there's no way to embed user-defined types.
只读
关键字应该做你所需要的,但是。通过与常量
相反,任何只读
字段将会在运行时初始化而不是编译的时候,这样他们就可以用更多的初始化以下任何你想表达
The readonly
keyword should do what you need, however. By contrast with const
, any readonly
fields get initialized at runtime rather than compile time, so they can be initialized with more or less any expression you want.
编辑:作为埃里克利珀指出的,它不是这个简单。例如,常量十进制
和
as Eric Lippert points out, it's not this straightforward. For instance, const decimal
works.
这:
private const decimal TheAnswer = 42;
...编译(当然,反光镜),以这样的:
...compiles (well, Reflectors) to this:
[DecimalConstant(0, 0, (uint) 0, (uint) 0, (uint) 42)]
private static readonly decimal TheAnswer;
这篇关于为什么不能nullables被声明为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!