如何制作一个录音工具的界面? [英] How to make a record implement an interface?
问题描述
如果我有一个界面:
type IData =
abstract member firstName: string
abstract member lastName: string
如何定义符合此接口的记录类型.
How do I define a record type that complies with this interface.
我尝试了以下操作:
> 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 ...'.
从官方参考进行记录:
记录字段与类的不同之处在于它们会自动显示为属性
Record fields differ from classes in that they are automatically exposed as properties
我的第一个问题是:如果属性是自动公开的",那么为什么我需要做一些事情"来实现它们.
My first question is: If properties are "automatically exposed" then why do I need to "do something" to implement them.
由于错误消息要求我提供该接口的实现,因此我尝试了以下操作:
Since the error message askes me to provide an implementation for the interface, I tried the following:
> 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
到目前为止还不错,但是现在当我尝试使用它时,我遇到了问题:
So far so good, however now when I try to use this, I run into issues:
> 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
类型的变量呢?
So, my second question is that if Data
implements IData
then why can't I assign a value of Data
type to a variable of IData
type ?
推荐答案
如 Gustavo 所指出的,隐式接口实现是F#实现者正在进行讨论,目前尚不可用.
As pointed by Gustavo, implicit interface implementation is being discussed by F# implementers, and is not currently available.
Wrt.我的第二个问题,需要显式强制转换:
Wrt. my second question, explicit casting is required:
> let d2: IData = d :> IData ;;
val d2 : IData = {firstName = "john";
lastName = "doe";}
这篇关于如何制作一个录音工具的界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!