定義類和介面

2021-09-30 11:20:51 字數 2546 閱讀 8510

定義類和介面

在 f# 中,有兩種方式為函式和類的成員定義引數:「curried」風格,成員可以散(partially)應用,「元組(tuple)」風格,所有成員都必須一次給定。定義類時,如使用元組風格,c# 客戶端可以更容易使用這樣的類。

看下面的例子,在 f# 中定義乙個類,其中有乙個curried 風格定義的成員curriedstyle,還有乙個元組風格的tuplestyle。

namespace strangelights

type democlass(z: int) =

//method in the curried style

memberthis.curriedstyle x y = x + y + z

//method in the tuple style

memberthis.tuplestyle (x, y) = x + y + z

從 c# 中檢視時,成員curriedstyle 的簽名是這樣的:

public fastfunccurriedstyle(int x)

而tuplestyle 則是這樣的簽名:

public int tuplestyle(int x, int y);

因此,如果想要從 c# 中使用這兩個成員,最終的**會似這樣的:

// !!! c# source !!!

using system;

usingstrangelights;

usingmicrosoft.fsharp.core;

class program ", result);

result= c.tuplestyle(4, 5);

console.writeline("tuple style result", result);

}static

void main(string args)

}從這個示例可以很明顯地看出,如果使用元組風格公開類的成員,庫使用者將會更滿意的。

namespacestrangelights

type idemointe***ce =

// method in the curried style

abstract curriedstyle: int-> int -> int

// method in the tupled style

abstract tuplestyle: (int* int) -> int

// method in the c# style

abstract csharpstyle: int* int -> int

// method in the c# style with named arguments

abstract csharpnamedstyle: x : int * y : int -> int

注意,oneargstyle 和multiargstyle 之間唯一的不同是後者不使用括號,在 f# 定義中的這一點不同,對從 c# 中的簽名卻有很大的影響。下面是前者的簽名:

int oneargstyle(tuple);

而後者的簽名是這樣的:

int multiargstyle(int, int);

對 c# 使用者來說,後者顯然更加友好一些。然而,我們也要付出一些,為每個引數新增名字。這並不改變 c# 使用者使用的簽名,當實現這個方法時,只改變在用visual studio 工具實現介面時看到的名字;此外,一些其他的.net 語言會把引數名看得很重要。這聽起來好像有點不同,但是,它使實現介面更加容易,因為,這種實現方法能夠更好地表達引數真正的意思。

下面的例子演示c# **實現在前面的例子中定義的介面idemointe***ce,很明顯,c# 使用者更樂於接收包含由 multiargstyle 或 namedargstyle 指定的方法的介面。

// !!! c# source !!!

using system;

usingstrangelights;

usingmicrosoft.fsharp.core;

// shows how toimplement an inte***ce

// that has been createdin f#

classdemoimplementation : idemointe***ce ;

// convert delegate to a fastfunc

return funcconvert.tofastfunc(d);

}// tuple style implementation

public

inttuplestyle(tuple t)

// c# style implementation

public

intcsharpstyle(int x, inty)

// c# style implementation, named arguments

// make no difference here

public

intcsharpnamedstyle(int x, int y) }[

這一段描述中的名字與實際**不符,但是,並不影響對文章的理解,故未訂正。

]

C 類和介面的定義

c 中的類定義 c 使用class關鍵字來定義類 class myclass 預設情況下,類宣告為內部的,即只有當前工程中的 才能訪問 也可以用internal關鍵字顯式宣告 internal class myclass 可以指定類是公共的,即可以由其他工程中的 來訪問 要用public關鍵字宣告 ...

泛型類介面定義

在使用泛型定義類的過程中遇到了不少問題,特記錄如下 定義最基本的泛型類如下 其實最簡單的只需要新增,就表示泛型類了,可在使用的過程中 pl.datalist new list 總是提示錯誤,編譯不通過,說是必須是類才可以,於是修改如下 public abstract class getdatabas...

定義和使用介面

宣告格式 訪問修飾符 inte ce 介面名 extends 父介面1,父介面2 定義介面的詳細說明 1.訪問修飾符 只能是public或缺省。2.介面名 和類名採用相同命名機制。3.extends 介面可以多繼承。4.常量 介面中的屬性只能是常量,總是 public static final 修飾...