操作员重载是一种方法, 通过该方法可以根据你的自定义需要重新定义操作员行为。你可以重载所有算术运算符。运算符必须定义为静态。所有一元运算符都必须使用〜(平铺)运算符表示这是一元运算符。
F#运算符重载示例
type OperatorOverloading(x: int, y : int) =
member this.X = x
member this.Y = y
static member (+) (v : OperatorOverloading, a) =
OperatorOverloading(a + v.X, a + v.Y)
override this.ToString() =
this.X.ToString() + " " + this.Y.ToString()
let operatorOverloading = OperatorOverloading(5, 3)
let operatorOverloading2 = operatorOverloading + 10
printfn "%s" (operatorOverloading.ToString())
printfn "%s" (operatorOverloading2.ToString())
输出:
5 3
15 13
评论前必须登录!
注册