“const correctness” in C#

前端 未结 7 1468
执念已碎
执念已碎 2020-11-28 05:29

The point of const-correctness is to be able to provide a view of an instance that can\'t be altered or deleted by the user. The compiler supports this by pointing out when

7条回答
  •  一整个雨季
    2020-11-28 05:37

    Interfaces are the answer, and are actually more powerful than "const" in C++. const is a one-size-fits-all solution to the problem where "const" is defined as "doesn't set members or call something that sets members". That's a good shorthand for const-ness in many scenarios, but not all of them. For example, consider a function that calculates a value based on some members but also caches the results. In C++, that's considered non-const, although from the user's perspective it is essentially const.

    Interfaces give you more flexibility in defining the specific subset of capabilities you want to provide from your class. Want const-ness? Just provide an interface with no mutating methods. Want to allow setting some things but not others? Provide an interface with just those methods.

提交回复
热议问题