【发布时间】:2015-02-23 14:30:04
【问题描述】:
为什么我在尝试对字符串调用 transform 时会出错?
type Truck = Truck
type Car = Car
type Vehicle<'a> =
| TruckWrapper of Truck * 'a
| CarWrapper of Car * 'a
type Truck with
member this.transform (x) = TruckWrapper(this, x)
type Car with
member this.transform (x) = CarWrapper(this, x)
type System.String with
member this.transform (x) =
match x with
| "truck" -> TruckWrapper(Truck, this)
| _ -> CarWrapper(Car, this)
let inline transform value x = (^T : (member transform : 'a -> Vehicle<'b>) (value, x))
let a = transform Truck 1
let b = transform Car (1, 2)
let c = transform "truck" 0
这将产生以下错误
let c = transform "truck" 0
------------------^^^^^^^
stdin(77,19): error FS0001: The type 'string' does not support the operator 'transform'
而
let d = "vehicle".transform("truck")
效果很好
【问题讨论】:
标签: f# extension-methods duck-typing