What's so bad about ref parameters?

后端 未结 12 597
隐瞒了意图╮
隐瞒了意图╮ 2021-01-11 09:49

I\'m faced with a situation that I think can only be solved by using a ref parameter. However, this will mean changing a method to always accept a ref parameter when I only

12条回答
  •  囚心锁ツ
    2021-01-11 10:35

    The biggest issue I have with ref parameters is they make it difficult to use type inference as you must sometimes explicitly declare the type of the variable being used as the ref parameter.

    Most of the time I use a ref parameter it's in a TryGet scenario. In general I've stopped using ref's in that scenario and instead opted for using a more functional style method by way of an option.

    For instance. TryGetValue in dictionary switches from

    bool TryGetValue(TKey key, out TValue value)
    

    To

    Option TryGetValue(TKey key)
    

    Option available here: http://blogs.msdn.com/jaredpar/archive/2008/10/08/functional-c-providing-an-option-part-2.aspx

提交回复
热议问题