[英]F# class not implementing interface function
I'm newbie to F# and experimenting it. 我是F#的新手,正在试验它。 I'm trying to implement a F# interface.
我正在尝试实现一个F#接口。
This is my F# file: 这是我的F#文件:
namespace Services.Auth.Domain
type IAuthMathematics =
abstract Sum : unit -> int
type AuthMathematics(a : int, b : int) =
member this.A = a
member this.B = b
interface IAuthMathematics with
member this.Sum() = this.A + this.B
When using it in C# and pressing F12, giving me this 在C#中使用它并按F12时,给我这个
[CompilationMapping(SourceConstructFlags.ObjectType)]
public class AuthMathematics : IAuthMathematics
{
public AuthMathematics(int a, int b);
public int A { get; }
public int B { get; }
}
[CompilationMapping(SourceConstructFlags.ObjectType)]
public interface IAuthMathematics
{
int Sum();
}
Where are my sum function and properties initialization ? 我的sum函数和属性初始化在哪里?
When you hit F12 from C# (I'm assuming that's Visual Studio, right?), it doesn't show you the source code (obviously - because the source is in F#), but rather it uses metadata to reconstruct what the code would look like if it was written in C#. 当你从C#点击F12时(我假设它是Visual Studio,对吧?),它没有显示源代码(显然 - 因为源代码是F#),而是它使用元数据重建代码会看起来好像是用C#编写的。 And while it's doing that, it shows only
public
and protected
things, because those are the only ones you can use anyway. 虽然它正在这样做,它只显示
public
和protected
东西,因为这些是你可以使用的唯一的。
At the same time, interface implementations in F# are always compiled as "explicit" , aka "private", so that's why they wouldn't show up in metadata-reconstructed view. 同时,F#中的接口实现总是被编译为“显式” ,即“私有”,这就是为什么它们不会出现在元数据重构视图中。
And of course, property initializers are part of the constructor's body, so naturally they're not shown either. 当然,属性初始值设定项是构造函数体的一部分,因此它们自然也没有显示出来。
For reference, your F# implementation would look something like this in C#: 作为参考,您的F#实现在C#中看起来像这样:
public class AuthMathematics : IAuthMathematics
{
public AuthMathematics(int a, int b) {
A = a;
B = b;
}
public int A { get; private set; }
public int B { get; private set; }
int IAuthMathematics.Sum() { return A + B; }
}
You can create an F# class that looks like a C# class with implicit interface member implementation. 您可以使用隐式接口成员实现创建一个看起来像C#类的F#类。 Because there is no implicit implementation in F#, you must both define the public member and implement the interface explicitly.
由于F#中没有隐式实现,因此必须同时定义公共成员并明确实现接口。 The result:
结果:
namespace Services.Auth.Domain
type IAuthMathematics =
abstract Sum : unit -> int
type AuthMathematics(a : int, b : int) =
member this.A = a
member this.B = b
member this.Sum() = this.A + this.B
interface IAuthMathematics with
member this.Sum() = this.Sum()
This is useful because it allows you to use the Sum()
method directly with an AuthMathematics
reference without having to cast to IAuthMathematics
. 这很有用,因为它允许您直接使用
Sum()
方法和AuthMathematics
引用,而无需转换为IAuthMathematics
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.