对F#中的字段及其访问规则以及初始化非常困惑
我们来上这节课:对F#中的字段及其访问规则以及初始化非常困惑,f#,F#,我们来上这节课: type Test() = let mutable Flag1 : bool = false [<DefaultValue>] val mutable Flag2 : bool do Flag1 <- true // that works Flag2 <- true // nope... why? member this.SetFlag = Flag1 <-
type Test() =
let mutable Flag1 : bool = false
[<DefaultValue>] val mutable Flag2 : bool
do
Flag1 <- true // that works
Flag2 <- true // nope... why?
member this.SetFlag =
Flag1 <- true // no 'this' instance? does that mean it's static?
this.Flag2 <- true // that works now, but still no way to set a default value
但是,既然它是实例的一部分,为什么语法val this.Flag1不存在呢?
和。。我无法从构造器访问它
有人能解释一下这是怎么回事吗?因为这很让人困惑。
如果不能在其中设置东西,那么构造函数的有用性似乎很低。或者,我错过了什么?
我不能通过一个新的()构造函数构造类的实例并设置变量,因为最后一条语句需要返回实例,所以我不能创建一个实例,设置所有需要的内容然后返回它。或者,可能吗
此外,我怎样才能有一个字段:
- 是一个实例字段,不是静态的
- 我可以在构造函数中初始化为我想要的任何内容
- 是可变的
- 可从成员函数访问
Class A
{
public Timer MyTimer;
public bool Flag1, Flag2;
A()
{
MyTimer = new Timer(Callback);
}
public void StartTimer()
{
MyTimer.Start();
}
public void Callback()
{
if (Flag1) Flag2 = true;
}
}
public class B : A
{
public void DoStuff()
{
Flag1 = True;
}
}
您需要为其所有主体指定类型实例别名:
type Test() (*here is the part you need: *) as this =
// ...
// and then you can access your public mutable field by type instance alias:
do this.Flag2 <- true
type Test()(*这是您需要的部分:*),因为这=
// ...
//然后可以按类型实例别名访问公共可变字段:
执行此操作。Flag2有一个有关构造函数初始化的相关问题。
Class A
{
public Timer MyTimer;
public bool Flag1, Flag2;
A()
{
MyTimer = new Timer(Callback);
}
public void StartTimer()
{
MyTimer.Start();
}
public void Callback()
{
if (Flag1) Flag2 = true;
}
}
public class B : A
{
public void DoStuff()
{
Flag1 = True;
}
}
type Test() (*here is the part you need: *) as this =
// ...
// and then you can access your public mutable field by type instance alias:
do this.Flag2 <- true