When is using the C# ref keyword ever a good idea?

后端 未结 10 962
情歌与酒
情歌与酒 2020-11-29 06:05

The more I see ref used in production code, the more misuse I encounter and the more pain it causes me. I have come to hate this keyword, because from a framework-building s

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 06:29

    I try to avoid it on public APIs, but it definitely has uses. Mutable value-types is an important one, especially on things like CF (where mutable structs are more common, due to platform requirements). However, perhaps the most common time I use it is when refactoring parts of a complex algorithm out into a few methods, where a state object is overkill and I need to pass multiple values around:

    i.e.

    var x = .....
    var y = .....
    // some local code...
    var z = DoSomethingSpecific(ref x, ref y); // needs and updates x/y
    // more local code...
    

    etc. Where DoSomethingSpecific is a private method, just moved out to keep method responsibility manageable.

提交回复
热议问题