F#在方法中为类成员赋值

时间:2009-06-11 23:46:55

标签: class syntax f#

我在VS 2010中玩F#,我无法弄清楚如何为类中的成员分配值。

type SampleGame = 
    class 
    inherit Game
    override Game.Initialize() = 
        spriteBatch <- new SpriteBatch(this.GraphicsDevice)
        base.Initialize()
    val mutable spriteBatch : SpriteBatch
    end

我认为这是对的,但它说无法找到“spriteBatch”。这是制作对象成员的正确方法,还是有更好的方法?

2 个答案:

答案 0 :(得分:3)

您应该更喜欢这种语法来定义类

type SampleGame() =     
    inherit Game()    
    let mutable spriteBatch : SpriteBatch = null
    override this.Initialize() =         
        spriteBatch <- new SpriteBatch(this.GraphicsDevice)        
        base.Initialize()    

你定义至少一个构造函数作为类定义的一部分(上面代码中第一个'SampleGame'之后的parens),然后使用'let'和'do'初始化/定义实例变量并运行代码为那个构造函数,然后最后定义方法/属性/覆盖/等。 (与您的语法相反,语法在类型名称后面没有构造函数的parens,并且对实例变量使用'val'。)

答案 1 :(得分:0)

我认为你必须在使用之前声明你的变量。

type SampleGame = 
    class 
    inherit Game

    val mutable spriteBatch : SpriteBatch

    override Game.Initialize() = 
        spriteBatch <- new SpriteBatch(this.GraphicsDevice)
        base.Initialize()
    end