[英]F# A value or constructor is not defined, even though using get and set
我是CS学生的第一年,也没有先前的编程知识。 我们刚刚完成了函数式编程,现在已经转向面向对象的编程了。 我正在做一项任务,我必须模仿动物之间的比赛。 给这些动物一些属性和方法,它们定义了它们的重量,最大速度等。代码的一个要求是它必须为每个被调用的实例生成一个随机变量来确定它的权重。 到目前为止,我已经在我的代码中达到了这一点:
let rnd = System.Random()
type Animal (name:string, animalWeight:float, maxSpeed:float) = class
let mutable foodInTakePercentage = float(rnd.Next(0,101))
member val animalMaxSpeed : float = maxSpeed with get, set
member val animalWeight = animalWeight with get, set
member val neccesaryFoodIntake = 0.0 with get, set
member val Name = name
new (name, maxSpeed) =
let minWeight = 70.0
let maxWeight = 300.0
let Weight = minWeight + rnd.NextDouble() * (maxWeight-minWeight)
Animal (name, Weight, maxSpeed)
member this.FoodInTakePercentage = foodInTakePercentage/100.0
member this.CurrentSpeed =
this.FoodInTakePercentage*maxSpeed
abstract FoodIntake : float
default this.FoodIntake = 0.5
member this.NeccesaryFoodIntake =
neccesaryFoodIntake <- animalWeight * FoodIntake
end
type Carnivore (name:string, animalWeight:float, maxSpeed:float) = class
inherit Animal (name, animalWeight, maxSpeed)
override this.FoodIntake = 0.08
end
type Herbivore (name:string, animalWeight:float, maxSpeed:float) = class
inherit Animal (name, animalWeight, maxSpeed)
override this.FoodIntake = 0.4
end
问题是,当编译它时,我收到错误消息:
10g.fsx(22,5): error FS0039: The value or constructor 'neccesaryFoodIntake' is not defined
我已经尝试了所有(我的知识非常有限),以便尝试将其定义为变量,但似乎没有任何效果。 有没有人有想法?
necessaryFoodIntake
的食物保险是一个集体成员,而不是一个独立的价值观。 要引用类成员,您需要指定该类的对象,例如x.necessaryFoodIntake
。
在您的代码中,感觉就像您正在尝试引用“ 当前 ”对象上的成员,这表示this
,因此您需要指定为对象:
member this.NeccesaryFoodIntake =
this.neccesaryFoodIntake <- animalWeight * FoodIntake
也就是说,使用NecessaryFoodIntake
成员想要实现的目标并不完全清楚。 你定义它的方式,它是一个带有getter的属性,并且getter实际上修改了另一个成员( necessaryFoodIntake
)并且不返回任何内容(即返回unit
)。 通常属性getter应该返回一个值而不是修改状态。
如果你确实想要定义一个修改某个内部状态并且不返回任何内容的成员,你应该(1)使它成为一个方法而不是属性,并且(2)将它命名为更合适的东西,例如
member this.CalculateNeccesaryFoodIntake() =
this.neccesaryFoodIntake <- animalWeight * FoodIntake
另一方面,如果您想要使用单个getter定义一个返回另一个成员的值的属性,则不应该修改任何内容:
member this.NeccesaryFoodIntake = this.neccesaryFoodIntake
但这有点无用,因为现在你有两个几乎相同的成员,除了其中一个是只读的。 如果你想从外面无法访问necessaryFoodIntake
FoodIntake然后提供NecessaryFoodIntake
作为它的公共接口,你应该让前者private
:
member val private neccesaryFoodIntake = 0.0 with get, set
总而言之,虽然我可以帮助您解决特定的语法错误,但其余的代码似乎也没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.