问题描述
因此,我是F#的新手,并且阅读了一些不同的教程,而我惊讶地发现它提到F#接口定义实际上可以包括成员方法的默认实现(使它们像虚拟方法一样工作). . 提到 都在这里:
So I'm new to F#, and reading a couple of different tutorials, and I was surprised to see it mentioned that F# interface definitions can actually include default implementations for member methods (making them act like virtual methods). This is mentioned both here:
http://www.tutorialspoint.com/fsharp/fsharp_interfaces.htm
http://www.tutorialspoint.com/fsharp/fsharp_interfaces.htm
在这里:
https://msdn.microsoft.com/zh-cn/visualfsharpdocs/conceptual/interfaces-%5Bfsharp%5D
https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/interfaces-%5Bfsharp%5D
我发现这很奇怪,因为接口的定义特征之一是它不包含任何实现. 但是更奇怪的是,我似乎无法在网络上的任何地方找到更多有关此的信息. 我链接的那两个页面 仅提及这是可能的,但不赘述或提供任何示例.
I find this rather odd as one of the defining characteristics of an interface is that it contains no implementation. But what's even more odd, is that I can't seem to find any more information on this anywhere on the web. Those two pages I link merely mention that this is a possibility, but don't go into any detail or provide any examples.
那么这是如何工作的? 如果我提供了接口函数的默认实现,它将如何使用? 在类中实现接口时是否可以简单地忽略实现该方法,而将使用默认实现? 我可以使用base关键字直接从覆盖实现中调用默认实现吗? 如果我在F#中定义了这样的接口,然后尝试在C#类定义中实现它,会发生什么? 任何为此建立的用例 行为?
So how does this work? If I provide a default implementation for an interface function, how does it get used? Can I simply neglect to implement that method when implementing the interface in a class and the default implementation will be used? Can I call the default implementation directly from my override implementation with the base keyword? What happens if I define such an interface in F#, then try to implement it in a C# class definition? Any established use cases for this behavior?
为什么没有在任何地方讨论这些内容?
And why isn't any of this discussed anywhere???
推荐答案
尝试(在F#3.0、3.1和4.0中)
Trying (in F# 3.0, 3.1 and 4.0)
type IPrintable = interface
abstract member Print : unit -> unit
default this.Print () = printfn "Hello, world!"
end
type SomeClass1(x: int, y: float) =
interface IPrintable with
member this.Print() = printfn "%d %f" x y
type SomeClass2() =
member this.Action () = printfn "act"
interface IPrintable
let x1 = new SomeClass1(1, 2.0)
(x1 :> IPrintable).Print()
let x2 = SomeClass2()
(x2 :> IPrintable).Print()
System.Console.ReadKey() |> ignore
收益
default this.Print () = printfn "Hello, world!"
----------------^^^^^
stdin(5,17): error FS0867: Interfaces cannot contain definitions of member overrides
将IPrintable的定义更改为
Changing the definition of IPrintable to
type IPrintable =
abstract member Print : unit -> unit
default this.Print () = printfn "Hello, world!"
改为定义一个抽象类,我们得到
defines an abstract class instead, and we get
interface IPrintable with
-------------^^^^^^^^^^
stdin(30,14): error FS0887: The type 'IPrintable' is not an interface type
符合消费者的期望.
as expected from the consumers.
这篇关于在F#接口定义中实现???的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!