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

前端 未结 4 1252
感情败类
感情败类 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.

提交回复
热议问题