Const methods in C#

后端 未结 4 650
悲&欢浪女
悲&欢浪女 2021-01-01 08:45

In C++, you can define a constant method like so:

int func_that_does_not_modify_this(int arg) const {}

Placing const at the en

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 08:54

    No, there's nothing like that in C#. It's been talked about a lot, but it's quite difficult to make const work in such a way that it's verifiable at compile time, can't be cast away like it can in C++, and is still reasonably easy to actually use without everyone having to get it perfectly right when they design their own classes.

    Of course, if you design your own types to be immutable (like string) then all instance methods on it are effectively const. This isn't always practical, but it's an important technique to use where appropriate.

提交回复
热议问题