F#类未实现接口功能

时间:2018-12-17 14:45:06

标签: c# f#

我是F#的新手,正在尝试它。我正在尝试实现F#接口。

这是我的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

在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();
}

我的sum函数和属性初始化在哪里?

2 个答案:

答案 0 :(得分:5)

当您从C#中按F12键(我假设是Visual Studio,对吗?),它不会向您显示源代码(显然-因为源代码位于F#中),而是使用元数据来重构如果使用C#编写,则代码看起来像。而且在执行此操作时,它仅显示publicprotected,因为无论如何您都只能使用它们。

同时,F#中的接口实现总是编译为"explicit",也称为“私有”,因此这就是为什么它们不会出现在元数据重构的视图中。

当然,属性初始值设定项是构造函数主体的一部分,因此自然也不会显示。

作为参考,您的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; }
}

答案 1 :(得分:0)

您可以创建一个F#类,该类看起来像具有隐式接口成员实现的C#类。由于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

    member this.Sum() = this.A + this.B

    interface IAuthMathematics with
        member this.Sum() = this.Sum()

这很有用,因为它允许您直接将Sum()方法与AuthMathematics引用一起使用,而不必强制转换为IAuthMathematics