c# - 当 this == null 和 obj == null 时调用 IEquatable<T>.Equals(T obj) 的结果?

标签 c# .net f# equals equality

应该做什么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) 类似的代码可以在问题“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/

相关文章:

c# - 仅当第二个 TSource 不为 Null 时联合集合

json - JToken 不像 JsonConvert.DeserializeObject 那样反序列化

f# - 此质因数分解代码适用于小数,但对于大数会因 OutOfMemoryException 而失败?

c# - 发布同一 ClickOnce 应用程序的多个版本的最佳方式是什么?

c# - 通过 Google Calendar API v3 创建重复事件

c# - 在 C#.net 中处理大量数据表的有效方法

c# - 尝试在运行时将 object[] 转换为 ValueType[]

c# - 在 Telerik RadGridView 中传递 DataContext

c# - 在 .Net 中使用 GDI+ 勾画路径

f# - 异步数据库查询