Understanding byref, ref and &

浪子不回头ぞ 提交于 2019-11-27 19:45:30

Ref keyword Yes, when you write let a = ref 10 you're essentially writing let a = new Ref<int>(10) where the Ref<T> 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<int> 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<int>, 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<int> 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...).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!