说,我有界面
type IAB =
abstract A: string
abstract B: string
type ICD =
abstract C: string
abstract D: string
我想构建一个实现IAB
和ICD
。
所以最简单的类型是:
type MyType =
{ A: string; B: string; C: string; D: string }
interface IAB with
member this.A = this.A
member this.B = this.B
interface ICD with
member this.C = this.C
member this.D = this.D
此代码看起来非常重复。当然我可以构建一个实现这些接口的普通类,但我觉得记录更适合这里,不是吗?
无论如何我可以改进吗?
答案 0 :(得分:2)
MyType
的定义略有偏差。它应该是:
type MyType = { A: string; B: string; C: string; D: string} with
interface IAB with
member x.A = x.A
member x.B = x.B
interface ICD with
member x.C = x.C
member x.D = x.D
如果您只使用了被转换为接口的类型,那么您可以使用:
type MyType(A: string, B: string, C: string, D: string) =
interface IAB with
member x.A = A
member x.B = B
interface ICD with
member x.C = C
member x.D = D
答案 1 :(得分:0)
F#没有像C#那样的接口的隐式语法。它在明确的方向上类似于C#:
C# Explicit Interface Implementation (tutorial)
此外,目前在F#中,您不能在同一类/类型中使用不同的泛型类型多次实现相同的接口。
这个区域有一些粗糙的边缘,而某些较高预算的更加优雅的CLR堂兄。
"" SOMTHING with"模式在F#等几个不同的地方使用,比如匹配语句。我知道我找到了这个语法,当我第一次遇到它时,你会勾勒出一些刺耳的声音,如果有任何安慰的话。但是,现在感觉很自然。