Sha*_*awn 14 c# null nullable const
[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似乎是要走的路
Tim*_*son 20
这不仅仅是毫无疑问的; 只能声明内置于运行时的类型const
(从内存,它是bools,各种类型的int,浮点数/双精度数和字符串).
为什么?因为该值在编译时直接嵌入到程序集中,并且无法嵌入用户定义的类型.
但是,readonly
关键字应该可以满足您的需求.相比之下const
,任何readonly
字段都在运行时而不是编译时初始化,因此可以使用或多或少的任何表达式初始化它们.
编辑:正如Eric Lippert指出的那样,这不是直截了当的.例如,const decimal
工作.
这个:
private const decimal TheAnswer = 42;
Run Code Online (Sandbox Code Playgroud)
...编译(好,反射器)到这个:
[DecimalConstant(0, 0, (uint) 0, (uint) 0, (uint) 42)]
private static readonly decimal TheAnswer;
Run Code Online (Sandbox Code Playgroud)
Bla*_*son 13
http://en.csharp-online.net/const,_static_and_readonly
常量必须是整数类型(sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal,bool或string),枚举或null引用.
由于类或结构在运行时使用new关键字初始化,而不是在编译时,因此无法为类或结构设置常量.
由于nullable是一个结构,因此上述引用就是原因所在.
你不能有一个const引用类型(或结构),因此你不能有一个const int?这真的只是一个Nullable<int>.
您可以将其标记为只读
readonly int? projectID = null;
Run Code Online (Sandbox Code Playgroud)
然后它不能在类构造函数之外修改.