CS0133 “The expression being assigned to 'identifier' must be constant” - what's the reason behind that?

前端 未结 4 1237
感情败类
感情败类 2020-12-03 16:47

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++          


        
相关标签:
4条回答
  • 2020-12-03 17:26

    const is meant to represent a compile-time constant... not just a read-only value.

    You can't specify read-only but non-compile-time-constant local variables in C#, I'm afraid. Some local variables are inherently read-only - such as the iteration variable in a foreach loop and any variables declared in the fisrt part of a using statement. However, you can't create your own read-only variables.

    If you use const within a method, that effectively replaces any usage of that identifier with the compile-time constant value. Personally I've rarely seen this used in real C# code.

    0 讨论(0)
  • 2020-12-03 17:29

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

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

    enum {
      count = buffer.Length;
    }
    

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

    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#)

    0 讨论(0)
  • 2020-12-03 17:33

    Also note that in C#, the modifier readonly is only available for member variables, not for local variables (i.e. defined inside a method).

    Microsoft probably should have been more specific in the C# reference guide:
    http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

    0 讨论(0)
  • 2020-12-03 17:50

    You can't assign a variable number to a const. It is a compile time constant.

    From the C# reference on const:

    A constant expression is an expression that can be fully evaluated at compile time.

    0 讨论(0)
提交回复
热议问题