2016-11-22 47 views
-1

在为RPG游戏定义库存系统时,我遇到了一个奇怪的问题。所以,我想要做的是添加一个玩家从商店中获得的物品。在添加时,我确保不要超过重量限制,如果它已经在我的库存包中,将增加物品的数量,否则我会明白地添加物品。IntelliSens在更新不可更改的值时未检测到类型属性

到目前为止,这看起来相当健全。我的问题是当我更新我的抽象类时,IntelliSens试图告诉我,我没有为我正在使用的类型定义该属性。实际上,它找不到抽象类的任何属性。可能是一个很糟糕的错误,但我已经在这个问题上困扰了很长时间,我希望得到一些支持!

UPDATE

这里的编译错误:类型 'InventoryItem' 不包含字段 '量' .. \ InventoryItems.fs 188件

[<AbstractClass>] 
    type InventoryItem() = 

    abstract member ItemName : string 

    abstract member ItemDescription : string 

    abstract member ItemWeight : float<kg> 

    abstract member ItemPrice : float<usd> 

    abstract member Quantity : int with get, set 


    let makeBagItemsDistinct (bag: InventoryItem array) = 
    bag |> Seq.distinct |> Seq.toArray 

    type Inventory = { 
     Bag : InventoryItem array 
     Weight: float<kg> 
    } 

    with 
     member x.addItem (ii: InventoryItem): Inventory = 
      if x.Weight >= MaxWeight <> true then x 
      elif (x.Weight + ii.ItemWeight) >= MaxWeight then x 
      else 
       let oItemIndex = x.Bag |> Array.tryFindIndex(fun x -> x = ii) 
       match oItemIndex with 
       | Some index -> 
        // There already an item of this type in the bag 
        let item = x.Bag |> Array.find(fun x -> x = ii) 
        let newBag = 
         x.Bag 
         |> Array.filter((<>) item) 
         |> Array.append [| { item with Quantity = item.Quantity +ii.Quantity |] 
         |> makeBagItemsDistinct 

        let inventory = { x with Bag = newBag } 
        { inventory with Weight = inventory.Weight + item.ItemWeight } 
       | None -> 
        let newBag = x.Bag |> Array.append [|ii|] |> makeBagItemsDistinct 
        let inventory = { x with Bag = newBag } 
        { inventory with Weight = inventory.Weight + ii.ItemWeight } 
+1

首先,您的缩进看起来不正确,请更正它。其次,请解释你所得到的错误,在何处,何时或以何种方式知道“它不工作”。 –

+1

我做了一些修改@FyodorSoikin。就像我之前提到的,编译器似乎没有在InventoryItem抽象类 –

+1

中看到我的数量字段您的缩进仍然处于关闭状态。而“似乎没有看到”不是一个问题的好描述。 –

回答

3

with keyword作品只记录。你正试图在课堂上使用它。

如果您希望始终在变更上复制InventoryItem,您可能想要切换到record,就像您已在使用Inventory一样。

+0

如果我还想更新一个抽象类,我该怎么去?我明白你在说什么,但肯定有,有办法吗? –

+0

如果您需要复制更改,则可以使用抽象的“With”方法克隆对象,并具有可选参数以更改克隆中的某些字段。但是每个孩子课都必须实施自己的“With”方法。这是很多样板。如果不需要C#interop,我会重新考虑使用抽象类,甚至是类。 – TheQuickBrownFox

+0

嗯,遇到此:https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/object-expressions 这将比你提供给我更好的答案。这正是我寻找的功能。我明白为什么在F#中使用DU和记录很棒,但我正在寻找一个覆盖我的类型创建的答案。 –

相关问题