[英]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#編寫的。 雖然它正在這樣做,它只顯示public
和protected
東西,因為這些是你可以使用的唯一的。
同時,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.