简体   繁体   English

F#在方法中为类成员分配值

[英]F# Assign Value to Class Member In Method

I'm playing around with F# in VS 2010 and i can't quite figure out how to assign a value to a member in a class. 我在VS 2010中玩F#,我不太清楚如何为类中的成员分配值。

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

I thought this was right but it says it cannot find "spriteBatch". 我以为这是对的,但是它说找不到“ spriteBatch”。 is this the correct way to make members for objects, or is there a better way? 这是为对象创建成员的正确方法,还是有更好的方法?

You should prefer this syntax for defining classes 您应该更喜欢使用这种语法来定义类

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

where you define at least one constructor as part of the class definition (the parens after the first 'SampleGame' in code above), and then next use 'let' and 'do' to initialize/define instance variables and run code for that constructor, and then finally define methods/properties/overrides/etc. 在其中,您至少定义一个构造函数作为类定义的一部分(上面代码中第一个“ SampleGame”之后的括号),然后接下来使用“ let”和“ do”来初始化/定义实例变量并为该构造函数运行代码,然后最终定义method / properties / overrides / etc。 (As opposed to your syntax which has no constructor parens after the type name and uses 'val' for instance variables.) (与您的语法相反,该语法在类型名称后没有构造器,并且将'val'用作实例变量。)

I think you have to declare your variable before you use them. 我认为您必须在使用变量之前声明变量。

type SampleGame = 
    class 
    inherit Game

    val mutable spriteBatch : SpriteBatch

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM