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...).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…