应该做什么IEquatable<T>.Equals(T obj)
什么时候做 this == null
和 obj == null
?
1) 此代码由F#编译器在执行IEquatable<T>
时生成.你可以看到它返回了 true
当两个对象都是 null
:
public sealed override bool Equals(T obj) { if (this == null) { return obj == null; } if (obj == null) { return false; } // Code when both this and obj are not null. }
2) 类似的代码可以在问题“in IEquatable implementation is reference check necessary”或问题“Is there a complete IEquatable implementation reference?”中找到。此代码返回 false
当两个对象都是 null
.
public sealed override bool Equals(T obj) { if (obj == null) { return false; } // Code when obj is not null. }
3) 最后一个选项是说方法的行为在this == null
时没有定义。 .
最佳答案
leppie 是对的。只是为了详细说明他的回答(并证实他怀疑 F# 不保证 this != null)
:可区分的联合可能标记有属性 [<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
允许用值 null 表示案例。 Option<'T>
就是这样一种类型。 None
情况在运行时由 null 表示。(None : option<int>).Equals(None)
在语法上是有效的。这是一个有趣的示例:
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type Maybe<'T> =
| Just of 'T
| Nothing
[<CompilationRepresentation(CompilationRepresentationFlags.Instance)>]
member this.ThisIsNull() = match this with Nothing -> true | _ -> false
反编译ThisIsNull
带反光镜显示
public bool ThisIsNull()
{
return (this == null);
}
结果:
Nothing.ThisIsNull() //true
关于c# - 当 this == null 和 obj == null 时调用 IEquatable<T>.Equals(T obj) 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8094930/