我正试图重写(=),以便能够将我新定义的类型与int进行比较。我想要实现这样的目标:
type T = T with static member op_Equality (_ : T, c : int) = true
let b = T = 2 // Error: This expression was expected to
// have type T but here has type int我可以很容易地使它在C#中工作,但在F#中却不能做到这一点。
我也试过
我想知道是否有可能让一个操作符与两种不同的类型一起工作?
发布于 2013-05-22 15:24:47
标准的=操作符假设这两个参数都具有相同的类型,因此我认为无法添加在不同类型上工作的重载。我认为一个明智的选择可能是定义一对运算符.=和=. (类似的运算符,例如.*和*.,通常用于标量乘法,标量分别位于左和右):
type Foo(n:int) =
member x.N = n
static member (=.) (x:Foo, y:int) = x.N = y
static member (.=) (y:Foo, x:int) = x.N = y但是,当用户想要比较不同类型的两个值时,最好只要求用户显式地编写a.N = y (因为严格地说,同一类型的两个值永远不可能相等--它们甚至不是同一类型的值!)
如果您真的愿意,可以重新定义=操作符,但我不建议这样做(而且,当您使用let定义运算符(=)时,编译器会给您一个警告,说明通常不建议这样做)。不管怎样,这可以用a trick described e.g. here来完成
type Foo(n:int) =
member x.N = n
// A type that contains all overloads of the `=`
// operator that you want to support
type Equality = EQ with
static member (?<-) (_:Equality, x:int, y:int) = x = y
static member (?<-) (_:Equality, x:float, y:float) = x = y
static member (?<-) (_:Equality, x:Foo, y:int) = x.N = y
// This hides the standard equality operator and can
// lead to all sorts of confusion! (Probably do not do this :-))
let inline (=) x y = (?<-) EQ x y
10 = 4
Foo(10) = 3也许您可以使用答案后面部分描述的方法定义您自己的操作符,但不要隐藏=,而是以不同的方式调用它。然后可以处理重载(以及标准类型),但不会隐藏标准定义。
https://stackoverflow.com/questions/16695288
复制相似问题