为什么不能将 nullable 声明为 const?
[TestClass]
public class MsProjectIntegration {
const int? projectID = null;
// The type 'int?' cannot be declared const
// ...
}
为什么我不能有 const int?
?
编辑: 我想要一个可空 int 作为 const 的原因是因为我只是使用它从数据库加载一些示例数据。如果它为空,我将在运行时初始化示例数据。这是一个非常快速的测试项目,显然我可以使用 0 或 -1,但 int?
感觉像是适合我想做的事情的正确数据结构。只读似乎是可行的方法
[TestClass]
public class MsProjectIntegration {
const int? projectID = null;
// The type 'int?' cannot be declared const
// ...
}
Why can't I have a const int?
?
Edit: 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这不仅仅是可空值;只有运行时内置的类型才能声明为 const(从内存中看,它是 bool、各种类型的 int、float/double 和字符串)。
为什么?因为该值在编译时直接嵌入到程序集中,并且无法嵌入用户定义的类型。
不过,
readonly
关键字应该可以满足您的需要。与 const 相比,任何 readonly 字段都会在运行时而不是编译时初始化,因此可以使用或多或少的任何您想要的表达式来初始化它们。编辑:正如 Eric Lippert 指出的那样,事情并不是这么简单。例如,
constdecimal
有效。这:
...编译(好吧,反射器)为:
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 withconst
, anyreadonly
fields get initialized at runtime rather than compile time, so they can be initialized with more or less any expression you want.Edit: as Eric Lippert points out, it's not this straightforward. For instance,
const decimal
works.This:
...compiles (well, Reflectors) to this:
http://en.csharp-online.net/const,_static_and_readonly
由于 nullable 是一个结构体,因此上面的引用就是原因。
http://en.csharp-online.net/const,_static_and_readonly
Since nullable is a struct, the above quote is the reason why.
你不能有一个 const 引用类型(或一个结构),因此你不能有一个 const int ?这实际上只是一个
Nullable。
您可以将其标记为只读,
然后就不能在类构造函数之外对其进行修改。
You can't have a const reference type (or a struct), therefore you can't have a const int? which is really just a
Nullable<int>.
You can mark it as readonly
Then it can't be modified outside the class constructors.
您可能需要考虑使用“readonly”修饰符。
const 在编译时评估,而 readonly 在运行时强制执行。复杂类型的实例无法编译到程序集中,因此必须在运行时创建。
You may want to consider using the "readonly" modifier instead.
const
s are evaluated at compile time, whereasreadonly
s are enforced at run time. Instances of complex types cannot be compiled into the assembly, and so must be created at runtime.你基本上是在说:
从逻辑的角度来看……声明本身没有任何意义。
You're basically saying:
From a logical point of view... the declaration itself makes no sense.