F#有许多不同的方法来定义类型中的变量/成员。我应该何时在F#中使用let
,member val
和member this.
,它们之间有什么区别?静态和可变成员怎么样?
答案 0 :(得分:21)
我发现更容易反编译正在发生的事情,所以:
type Region() =
let mutable t = 0.0f
member val Width = 0.0f
member x.Height = 0.0f
member val Left = 0.0f with get,set
member x.Top with get() = 0.0f and set(value) = t <- value
实际上如下:
public class Region
{
internal float t;
internal float Width@;
internal float Left@;
public float Width
{
get
{
return this.Width@;
}
}
public float Height
{
get
{
return 0f;
}
}
public float Left
{
get
{
return this.Left@;
}
set
{
this.Left@ = value;
}
}
public float Top
{
get
{
return 0f;
}
set
{
this.t = value;
}
}
public Region() : this()
{
this.t = 0f;
this.Width@ = 0f;
this.Left@ = 0f;
}
}
答案 1 :(得分:10)
此示例解释了语法之间的区别:
type MyClass() =
let random = new System.Random()
[<DefaultValue>] val mutable field : int
member val AutoProperty = random.Next() with get, set
member this.ExplicitProperty = random.Next()
let c = new MyClass()
// class1.random is not accessible
c.field <- 42 // 'field' is accessible
// An automatic property is only evaluated upon initialization, and not every time the property is accessed
printfn "AutoProperty = %d" c.AutoProperty // x
printfn "AutoProperty = %d" c.AutoProperty // Still x
// The value of the explicit property is evaluated each time
printfn "ExplicitProperty = %d" c.ExplicitProperty // y
printfn "ExplicitProperty = %d" c.ExplicitProperty // The value is re-evaluated so you'll get a different value