当此== null且o​​bj == null时调用IEquatable <T> .Equals(T obj)的结果?

Rad*_*cek 8 .net c# f# equality equals

应该怎样IEquatable<T>.Equals(T obj)做时,this == nullobj == 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.

    public sealed override bool Equals(T obj)
    {
        if (obj == null)
        {
            return false;
        }

        // Code when obj is not null.
    }

3)最后一个选项是说没有定义方法的行为this == null.

Dan*_*iel 9

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
Run Code Online (Sandbox Code Playgroud)

ThisIsNull使用Reflector进行反编译显示

public bool ThisIsNull()
{
    return (this == null);
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

Nothing.ThisIsNull() //true
Run Code Online (Sandbox Code Playgroud)