开发者

Is == guaranteed to work when comparing objects loaded from NHibernate?

开发者 https://www.devze.com 2023-03-30 19:26 出处:网络
Here\'s what we know: It\'s recommended by NHibernate to override Equals() and GetHashCode(). It\'s recommended by Microsoft that you NOT override operator == in non-immutable types. It seems, therefo

Here's what we know: It's recommended by NHibernate to override Equals() and GetHashCode(). It's recommended by Microsoft that you NOT override operator == in non-immutable types. It seems, therefore, that client code should not be using开发者_如何学运维 operator== to compare objects. For example, assuming Foo overloads GetHashCode() and Equals correctly, then:

var foo1 = session.Get<Foo>(23);

 ...

var foo2 = session.Get<Foo>(23);

Assert.IsTrue( foo1 == foo2 );  // May fail!
Assert.IsTrue( foo1.Equals(foo2)); // Guaranteed!

Is this a correct summation?


The Hibernate session guarantees that both get-calls in your sample code would actually return the same object instance.

So in the case of persistent hibernate objects belonging to the same session the == operator would work reliably.


I believe that your summation is correct. Equals() is an equality comparison. With a simple type like a string or an int == is guaranteed to work, but with an object I believe you're better off using Equals().


The equality operator == will do an reference equality comparison. E.g. does the reference of foo1 equal the reference of foo2.

0

精彩评论

暂无评论...
验证码 换一张
取 消