Understanding byref, ref and &

前端 未结 1 1124
长发绾君心
长发绾君心 2020-12-05 05:02

Well, I came to understand that F# is able to manage references (some sort of C++ like references). This enables the possibilities to change value of parameters passed in fu

1条回答
  •  离开以前
    2020-12-05 05:21

    Ref keyword Yes, when you write let a = ref 10 you're essentially writing let a = new Ref(10) where the Ref type has a mutable field Value.

    Access value The := and ! operators are just shortcuts for writing:

    a.Value <- 10  // same as writing: a := 10
    a.Value        // same as writing: !a
    

    ByRef is a special type that can be (reasonably) used only in method parameters. It means that the argument should be essentially a pointer to some memory location (allocated on heap or stack). It corresponds to out and ref modifiers in C#. Note that you cannot create local variable of this type.

    The & operator is a way to create a value (a pointer) that can be passed as an argument to a function/method expecting a byref type.

    Calling functions the example with byref works because you're passing the method a reference to a local mutable variable. Via the reference, the method can change the value stored in that variable.

    The following doesn't work:

    let a = 10            // Note: You don't even need 'mutable' here
    bar.Increment(ref a)  
    

    The reason is that you're creating a new instance of Ref and you're copying the value of a into this instance. The Increment method then modifies the value stored on heap in the instance of Ref, but you don't have a reference to this object anymore.

    let a = ref 10
    bar.Increment(a)  
    

    This works, because a is a value of type Ref and you're passing a pointer to the heap-allocated instance to Increment and then get the value from heap-allocated reference cell using !a.

    (You can use values created using ref as arguments for byref because the compiler handles this case specially - it will automatically take reference of the Value field because this is a useful scenario...).

    0 讨论(0)
提交回复
热议问题