1

对于我的一个项目,我需要一个可以携带多种类型的列表,并且我不想做任何转换,所以我尝试使用obj lists. 下面是一些示例代码来展示一些应该可以工作的东西,但由于某种原因不能:

type Fruit() =
  member this.Kind = "I'm a tasty fruit!"

type Apple() =
  inherit Fruit()
  member this.Kind = "I'm a crispy apple!"

type Cherry() =
  inherit Fruit()
  member this.Kind = "I'm a juicy cherry!"


> (new Fruit()).Kind
val it : string = "I'm a tasty fruit!"

... // And so on; it works as expected for all three fruits

> let aFruit = [new Fruit()]
val aFruit : Fruit list = [FSI_0002+Fruit]

> aFruit.Head.Kind                          // Works just fine
val it : string = "I'm a tasty fruit!"

> let fruits : obj list = [new Fruit(); new Apple(); new Cherry]
val fruits : obj list = [FSI_0002+Fruit; FSI_0002+Apple; FSI_0002+Cherry]

> fruits.Head                               // Okay, so we can extract items just fine. It also kept the property!
val it : obj = FSI_0002+Fruit {Kind = "I'm a tasty fruit!";}

> it.Kind                                   // This doesn't work. Why? What am I missing?
 error FS0039: The field, constructor or member 'Kind' is not defined
4

1 回答 1

3

问题是it具有类型obj,因为列表是一个obj list并且obj没有.Kind成员。您可以使用父类型 - 比如

let fruits : Fruit list = [new Fruit(); new Apple(); new Cherry()];;

val fruits : Fruit list = [FSI_0003+Fruit; FSI_0003+Apple; FSI_0003+Cherry]

然后通过以下方式访问它:

fruits.Head.Kind;;
val it : string = "I'm a tasty fruit!"
于 2012-11-13T02:28:58.070 回答