为什么我不能在 C# 中使用 var 声明常量?
this:
const int a = 5;
编译得很好,但
const var a = 5;
不行... while:
var a = 5;
编译得和 this:
int a = 5;
为什么?
this:
const int a = 5;
compiles just fine, whereas
const var a = 5;
doesn't... while:
var a = 5;
compiles just as well as this:
int a = 5;
why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
var
关键字的目的是让您免于编写长而复杂的类型名,这些类型名不能是常量。能够编写这样的声明非常方便:
使用匿名类型时,它变得必要。
对于常量,这不是问题。
具有常量文字的最长内置类型名是十进制;这不是一个很长的名字。
可以有任意长的
enum
名称来用作常量,但 C# 编译器团队显然并不关心这一点。一方面,如果您要创建一个常量
enum
值,您不妨将其放入enum
中。另外,
enum
名称不应该太长。 (与复杂的泛型类型不同,复杂的泛型类型可以并且经常应该)The
var
keyword was intended to save you from writing long complex typenames, which cannot be constants.It is very convenient to be able to write declarations like
It becomes necessary when using anonymous types.
For constants, this isn't an issue.
The longest built-in typename with constant literals is
decimal
; that's not a very long name.It is possible to have arbitrarily long
enum
names which can be used as constants, but the C# compiler team apparently wasn't concerned for that.For one thing, if you're making a constant
enum
value, you might as well put it in theenum
.Also,
enum
names shouldn't be too long. (Unlike complex generic types, which can and frequently should)这是一个编译器限制,Eric Lippert 给出了该限制的原因 这里
It is a compiler limitation, and the reason for that limitation is given by Eric Lippert here
不带 var 的常量:
带 var 的常量(匿名类型属性值创建后无法更改):
Constants without var:
Constants with var (anonymous type property values cannot be changed after creation):
由于常量必须是内置数字类型或字符串,因此您实际上并没有节省太多;
const int
与const var
的长度相同,并且int
可能是最常见的常量类型。然后是 double ,它实际上并没有那么长。如果您有很多要输入的内容,请使用 Alt 选择功能;-)Since constants must be built-in numeric types or
string
, you don't really save much;const int
is the same length asconst var
andint
is probably the most common type of constant. Then there'sdouble
which is really not all that long. If you have a lot of them to type, use the Alt selection feature ;-)