如果我有一个界面:
type IData =
abstract member firstName: string
abstract member lastName: string
如何定义符合此界面的记录类型。
我尝试过类似下面的内容:
> type Data = { firstName: string; lastName: string } interface IData ;;
Snippet.js(43,63): error FS0366: No implementation was given for 'abstract member IData.firstName : string'. Note that all interface members must be implemented
and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'.
来自记录的official reference:
记录字段与类的不同之处在于它们会自动显示为属性
我的第一个问题是:如果属性“自动暴露”,那么为什么我需要“做某事”来实现它们。
由于错误消息要求我提供接口的实现,我尝试了以下内容:
> type Data = { firstName: string; lastName: string; } interface IData with
- member this.firstName with get () = this.firstName
- member this.lastName with get () = this.lastName
type Data =
{firstName: string;
lastName: string;}
with
interface IData
end
到目前为止一直很好,但是现在当我尝试使用它时,我遇到了问题:
> let d: IData = { firstName = "john"; lastName = "doe" } ;;
error FS0001: This expression was expected to have type
'IData'
but here has type
'Data'
另一种尝试:
> let d = { firstName = "john"; lastName = "doe" }
- ;;
val d : Data = {firstName = "john";
lastName = "doe";}
> let d2: IData = d ;;
C:\Users\loref\Workspace\source-nly10r\Untitled-1(25,17): error FS0001: This expression was expected to have type
'IData'
but here has type
'Data'
所以,我的第二个问题是,如果Data
实现IData
,为什么我不能将Data
类型的值分配给IData
类型的变量?< / p>
答案 0 :(得分:3)
正如Gustavo所指出的,F#实现者的隐式接口实现是being discussed,目前不可用。
WRT。我的第二个问题,需要明确的施法:
> let d2: IData = d :> IData ;;
val d2 : IData = {firstName = "john";
lastName = "doe";}