F#类没有实现接口函数

  • 本文关键字:接口 函数 实现 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函数和属性初始化在哪里?

当您从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; }
}

您可以创建一个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

最新更新