【发布时间】:2017-09-10 20:35:06
【问题描述】:
F# 记录不能被继承,但它们可以实现接口。比如我想创建不同的控制器:
type ControllerType =
| Basic
| Advanced1
| Advanced1RAM
| Advanced1RAMBattery
| Advanced2
// base abstract class
type IController =
abstract member rom : byte[]
abstract member ``type`` : ControllerType
type BasicController =
{ rom : byte[]
``type`` : ControllerType }
interface IController with
member this.rom = this.rom
member this.``type`` = this.``type``
type AdvancedController1 =
{ ram : byte[]
rom : byte[]
``type`` : ControllerType }
interface IController with
member this.rom = this.rom
member this.``type`` = this.``type``
type AdvancedController2 =
{ romMode : byte
rom : byte[]
``type`` : ControllerType }
interface IController with
member this.rom = this.rom
member this.``type`` = this.``type``
let init ``type`` =
match ``type`` with
| Basic ->
{ rom = Array.zeroCreate 0
``type`` = Basic } :> IController
| Advanced1 | Advanced1RAM | Advanced1RAMBattery ->
{ ram = Array.zeroCreate 0
rom = Array.zeroCreate 0
``type`` = ``type`` } :> IController
| Advanced2 ->
{ romMode = 0xFFuy
rom = Array.zeroCreate 0
``type`` = ``type`` } :> IController
我有两个问题:
- 当我创建一个控制器记录时,我需要将它上传到一个接口。没有
:> IController每条记录,有没有更好的方法来编写上面的init函数? - 我尝试了有区别的联合,但不知何故最终编写了像这个例子这样的接口。但是接口是 .NET 的东西,我怎样才能以功能的方式重写示例,使用组合而不是继承?
【问题讨论】:
标签: c# .net f# functional-programming record