什么应该IEquatable<T>.Equals(T obj)
何时做this == null
and 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)类似的代码可以在问题“在 IEquatable 实现中,引用检查是必要的“或者在问题中”有完整的 IEquatable 实现参考吗?”。此代码返回false
当两个对象都是null
.
莱皮是对的。只是为了详细说明他的答案(并证实他的怀疑,F# 不能保证this != null)
:可区分的联合可以用属性标记[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
允许用 null 值来表示事例。Option<'T>就是这样一种类型。这None
case 在运行时用 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)