我可以为结构类型的参数重载“=”运算符吗?

Can I overload the '=' operator for struct-typed arguments?

我想在任何对结构类型参数使用等号运算符“=”的地方都收到警告。似乎如果我定义这个运算符它不会重载,它只是重新定义'='以仅适用于结构类型的参数,这不是我想要的。

[<Obsolete("Possible performance issue with '=' operator on structs. See https://github.com/dotnet/fsharp/issues/526.")>]
let inline (=) (x:  ^T) (y:  ^T) : bool when   ^T: struct and ^T: (static member (=) :  ^T *  ^T -> bool) =
    x = y

let a = obj()
let x = Guid.NewGuid()
let y = Guid.NewGuid()

a = a |> ignore // oh no - "A generic construct requires that the type 'obj' is a CLI or F# struct type."

x = y |> ignore // ok - gets desired warning

这可以在 F# 中按原样完成吗?

更新: 找到了一个可能的解决方法:只需在受影响的结构上使用 [] 属性;这确实意味着所有结构都需要注释,但至少它确实有帮助。

不,您不能仅在某些情况下重新定义 globally-scoped(即 non-member)函数。一旦函数在范围内,它将始终被使用,不会回退到先前定义的函数。