CS0133"这位前pression被分配到'标识'必须是恒定QUOT; - 什么是背后的原因是什么?标识、分配、原因、QUOT

2023-09-02 02:03:55 作者:雾散

通过大量的C ++背景,我习惯了写如下:

With a lot of C++ background I've got used to writing the following:

const int count = ...; //some non-trivial stuff here
for( int i = 0; i < count; i++ ) {
   ...
}

和我的预期,同样会正常工作在C#。但是...

and I expected that the same would work fine in C#. However...

byte[] buffer = new byte[4];
const int count = buffer.Length;

生成的错误CS0133:这位前pression被分配到计数必须是常量的

我不明白这一点。这是为什么无效? INT 是值类型,不是吗?为什么我不能指定一个值,并把这些变量不变的这种方式?

I don't get it. Why is that invalid? int is a value type, isn't it? Why can't I assign a value and make the variable unchangeable this way?

推荐答案

由于常量在C#中是一个很大的常量常量在C ++中。 ;)

Because const in C# is a lot more const than const in C++. ;)

在C#中,常量是用来表示一个编译时间常数EX pression。这将会是类似这样的C ++ code:

In C#, const is used to denote a compile-time constant expression. It'd be similar to this C++ code:

enum {
  count = buffer.Length;
}

由于 buffer.Length 在运行时进行评估,它不是一个恒定的前pression,所以这会产生一个编译错误。

Because buffer.Length is evaluated at runtime, it is not a constant expression, and so this would produce a compile error.

C#有一个只读关键字这是一个比较类似于C ++的常量。 (它仍然非常有限,虽然,有没有这样的东西为const,正确性在C#)

C# has a readonly keyword which is a bit more similar to C++'s const. (It's still much more limited though, and there is no such thing as const-correctness in C#)