简体   繁体   English

F#对象列表

[英]F# object lists

For a project of mine, I need a list that can carry multiple types, and I don't want to do any casting, so I've tried using obj list s. 对于我的项目,我需要一个可以携带多种类型的列表,我不想做任何转换,所以我尝试使用obj list s。 Here's some example code to show something that should work, but for some reason doesn't: 这是一些示例代码,用于显示应该有效的内容,但由于某种原因不能:

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

The problem is that it has type obj as the list is an obj list and obj has no .Kind member. 问题是it有类型obj因为列表是一个obj listobj没有.Kind成员。 You can use the parent type - like 你可以使用父类型 - 比如

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

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

and then access it with: 然后使用以下命令访问它:

fruits.Head.Kind;;
val it : string = "I'm a tasty fruit!"

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

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