Why does C# disallow readonly local variables?

后端 未结 13 1167
萌比男神i
萌比男神i 2020-11-27 17:17

Having a friendly debate with a co-worker about this. We have some thoughts about this, but wondering what the SO crowd thinks about this?

13条回答
  •  离开以前
    2020-11-27 18:04

    Addressing Jared's answer, it would probably just have to be a compile-time feature - the compiler would prohibit you from writing to the variable after the initial declaration (which would have to include an assignment).

    Can I see value in this? Potentially - but not a lot, to be honest. If you can't easily tell whether or not a variable is going to be assigned elsewhere in the method, then your method is too long.

    For what it's worth, Java has this feature (using the final modifier) and I've very rarely seen it used other than in cases where it has to be used to allow the variable to be captured by an anonymous inner class - and where it is used, it gives me an impression of clutter rather than useful information.

提交回复
热议问题