且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

哪些类型可以声明为const?

更新时间:2022-06-23 22:50:01

很好 MSDN 明确指出


常量表达式是可以在
编译时完全评估的表达式。因此,
引用类型的常量的唯一可能值为字符串和null。

A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and null.

来自C#语言规范的10.4节。可以使用这些类型。

From section 10.4 of C# language specification. These are the types that can be used.


在常量声明中指定的类型必须是sbyte,byte,
short, ushort,int,uint,long,ulong,char,float,double,decimal,
bool,字符串,枚举类型或引用类型。每个
常量表达式都必须产生目标类型或
类型的值,可以通过隐式转换将其转换为目标类型

The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. Each constant-expression must yield a value of the target type or of a type that can be converted to the target type by an implicit conversion