Why is there no const member method in C# and const parameter?

后端 未结 3 563

Unlike C++, there aren\'t any const member method and const parameters in C#. What is the reason?

3条回答
  •  时光说笑
    2020-12-09 17:36

    First off, there is no requirement that we provide a reason for not implementing a feature. Features are extremely expensive; there has to be a justification for implementing a feature, not a justification for not implementing a feature.

    Second, C# is not a clone of C++ or C. Just because a feature is in some other language is not a reason to put it in C#.

    Third, "const" is deeply, tragically broken in C and C++. "const" gives you no guarantee that you can actually rely upon. If you are the caller of a method that takes a const reference then you have no guarantee whatsoever that the method honours the constness; the method has many ways of mutating a const reference. If you are the consumer of a const reference then you have no guarantee that the underlying object actually will not mutate arbitrarily. Since the contract is not enforced on either the caller or the callee side, it is far weaker than any other guarantee that we would like to make in the type system. We would not want to replicate such a broken system.

    Fourth, putting constness in the CLR type system means that every language would have to use the same implementation of constness; since different languages have different meanings for constness, that would be making it harder to bring more languages to the CLR, not easier.

    There are many reasons for not doing this extremely expensive feature, and very few reasons to do it. Expensive, unjustified features don't get implemented.

提交回复
热议问题