繁体   English   中英

F#类没有实现接口函数

[英]F# class not implementing interface function

我是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函数和属性初始化在哪里?

当你从C#点击F12时(我假设它是Visual Studio,对吧?),它没有显示源代码(显然 - 因为源代码是F#),而是它使用元数据重建代码会看起来好像是用C#编写的。 虽然它正在这样做,它只显示publicprotected东西,因为这些是你可以使用的唯一的。

同时,F#中的接口实现总是被编译为“显式” ,即“私有”,这就是为什么它们不会出现在元数据重构视图中。

当然,属性初始值设定项是构造函数体的一部分,因此它们自然也没有显示出来。

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

您可以使用隐式接口成员实现创建一个看起来像C#类的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

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

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

这很有用,因为它允许您直接使用Sum()方法和AuthMathematics引用,而无需转换为IAuthMathematics

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM