我正在使用F#进行小型程序只是为了进行个人训练并得到一些时刻,这是我无法解决的.
我正在描述一些界面:
type I?alculations = abstract member Add : int * int -> int abstract member Subtract : int * int -> int abstract member Multiply : int * int -> int abstract member Divide : int * int -> int
如您所见,除名称外的成员签名是相同的.
我可以使用F#进行下一步(现在将是伪代码):
let names = [ "Add", "Subtract", "Multiply", "Divide" ]; let ICalculations = new interface; foreach ( name in names ) { ICalculations[ name ] : int * int -> int }
目的不是为每个成员重复签名 int * int -> int
可能吗?
接口声明后,您无法定义接口方法类型.但是你可以定义例如Dictionary,包含你的类型的函数:
open System.Collections.Generic type Ops = Add | Subtract | Multiply | Divide let pseudoInterface = Dictionaryint>() // Then somewhere in your program you could define this "methods" pseudoInterface.[Add] <- fun (i, j) -> i + j pseudoInterface.[Subtract] <- fun (i, j) -> i - j // etc...
或者,您可以为函数类型定义类型别名,以简化:
type Op = int * int -> int type I?alculations = abstract member Add : Op abstract member Subtract : Op abstract member Multiply : Op abstract member Divide : Op