相关疑难解决方法(0)

Equals和GetHashCode的最佳策略是什么?

我正在使用域模型,并且正在思考我们在.NET中实现这两种方法的各种方法.你最喜欢的策略是什么?

这是我目前的实施:

public override bool Equals(object obj)
{
    var newObj = obj as MyClass;

    if (null != newObj)
    {
        return this.GetHashCode() == newObj.GetHashCode();
    }
    else
    {
        return base.Equals(obj);
    }
}

// Since this is an entity I can use its Id
// When I don't have an Id, I usually make a composite key of the properties
public override int GetHashCode()
{
    return String.Format("MyClass{0}", this.Id.ToString()).GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)

.net c# equals gethashcode

36
推荐指数
3
解决办法
1万
查看次数

标签 统计

.net ×1

c# ×1

equals ×1

gethashcode ×1