zaj*_*jer 1 f# interface interface-implementation
假设我在 F# 中有以下接口:
type InterfaceA =
abstract Magic : InterfaceA -> InterfaceA
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这样的接口?当我尝试这样做时:
type MyTypeA = {x:int} with
interface InterfaceA with
member self.Magic another =
{x=self.x+another.x}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
This expression was expected to have type 'InterfaceA' but here has type 'MyTypeA'
要修复类型错误,您需要将返回值显式转换为类型InterfaceA- 与 C# 不同,F# 不会自动执行此操作:
type InterfaceA =
abstract Magic : InterfaceA -> InterfaceA
abstract Value : int
type MyTypeA =
{x:int}
interface InterfaceA with
member self.Value = self.x
member self.Magic another =
{ x=self.x+another.Value } :> InterfaceA
Run Code Online (Sandbox Code Playgroud)
请注意,您的代码也不起作用,因为它another是类型InterfaceA,因此它没有x您可以访问的字段。为了解决这个问题,我Value向界面添加了一个成员。
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |