为什么我不能在 C# 中使用 var 声明常量?

发布于 2024-11-09 11:44:05 字数 259 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风和你 2024-11-16 11:44:05

var 关键字的目的是让您免于编写长而复杂的类型名,这些类型名不能是常量。

能够编写这样的声明非常方便:

var dict = new Dictionary<string, List<Definition>>();

使用匿名类型时,它变得必要

对于常量,这不是问题。
具有常量文字的最长内置类型名是十进制;这不是一个很长的名字。

可以有任意长的 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

var dict = new Dictionary<string, List<Definition>>();

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 the enum.
Also, enum names shouldn't be too long. (Unlike complex generic types, which can and frequently should)

空城仅有旧梦在 2024-11-16 11:44:05

这是一个编译器限制,Eric Lippert 给出了该限制的原因 这里

It is a compiler limitation, and the reason for that limitation is given by Eric Lippert here

羞稚 2024-11-16 11:44:05

不带 var 的常量:

const int Value1 = 1;
const int Value2 = 2;

带 var 的常量(匿名类型属性值创建后无法更改):

var constants = new { 
  Value1 = 1, 
  Value2 = 2,
};
//use as constants.Value1

Constants without var:

const int Value1 = 1;
const int Value2 = 2;

Constants with var (anonymous type property values cannot be changed after creation):

var constants = new { 
  Value1 = 1, 
  Value2 = 2,
};
//use as constants.Value1
音栖息无 2024-11-16 11:44:05

由于常量必须是内置数字类型或字符串,因此您实际上并没有节省太多; const intconst 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 as const var and int is probably the most common type of constant. Then there's double which is really not all that long. If you have a lot of them to type, use the Alt selection feature ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文