F# 和接口实现的成员 [英] F# and interface-implemented members

查看:23
本文介绍了F# 和接口实现的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个令人烦恼的错误.

I have a vexing error.

type Animal =

    abstract member Name : string

type Dog (name : string) =

    interface Animal with

        member this.Name : string =
            name

let pluto = new Dog("Pluto")
let name = pluto.Name

最后一行,特别是Name"会生成一个编译器错误,指出未定义字段、构造函数或成员‘Name’".

The last line, specifically "Name" generates a compiler error saying that "the field, constructor or member 'Name' is not defined".

我使用的解决方法是编写

The workaround I've used is to write

let name = (pluto :> Animal).Name

然而,这很烦人,并且会产生很多视觉噪音.是否可以在 F# 中做一些事情来解析 Name,而无需明确告诉编译器 Name 是 Animal 类型的派生成员?

However this is very annoying and creates a lot of visual noise. Is there something one can do in F# to just be able to resolve Name without telling the compiler explicitly that Name is a derived member from the Animal type?

推荐答案

在 F# 中,当你实现一个接口时,它相当于 C# 中的显式接口实现.即可以通过接口调用方法,不能直接通过类调用.

In F#, when you implement an interface, it's an equivalent of explicit interface implementation in C#. That is, you can call the method through the interface, but not directly through the class.

关于接口的 F# 参考文章 建议添加一个对类型执行向上转换的方法:

F# reference article about interfaces suggests adding a method that does the upcasting to the type:

type Dog (name : string) =

    member this.Name = (this :> Animal).Name

    interface Animal with
        member this.Name : string = name

或者,按照 Daniel 的建议,你可以反过来做,这意味着你可以避免这种转换:

Or, as suggested by Daniel, you can do it the other way around, which means you can avoid that cast:

type Dog (name : string) =

    member this.Name = name

    interface Animal with
        member this.Name : string = this.Name

此外,接口名称的 .Net 约定是以 I 开头,因此您的接口应称为 IAnimal.

Also, the .Net convention for interface names is to start them with I, so your interface should be called IAnimal.

这篇关于F# 和接口实现的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆