संदर्भ प्रकारों के लिए समानता() कार्यान्वित करना ऐसा लगता है जितना कठिन लगता है। मेरे वर्तमान विहित कार्यान्वयन इस प्रकार है:संदर्भ प्रकारों के लिए बराबर() के "सर्वोत्तम" कैननिकल कार्यान्वयन क्या है?
public bool Equals(MyClass obj)
{
// If both refer to the same reference they are equal.
if(ReferenceEquals(obj, this))
return true;
// If the other object is null they are not equal because in C# this cannot be null.
if(ReferenceEquals(obj, null))
return false;
// Compare data to evaluate equality
return _data.Equals(obj._data);
}
public override bool Equals(object obj)
{
// If both refer to the same reference they are equal.
if(ReferenceEquals(obj, this))
return true;
// If the other object is null or is of a different types the objects are not equal.
if(ReferenceEquals(obj, null) || obj.GetType() != GetType())
return false;
// Use type-safe equality comparison
return Equals((MyClass)obj);
}
public override int GetHashCode()
{
// Use data's hash code as our hashcode
return _data.GetHashCode();
}
मुझे लगता है कि यह सब कोने (विरासत और इस तरह के) के मामलों को शामिल किया गया लेकिन मैं गलत हो सकता है। आप लोग क्या सोचते हैं?
मेरा कार्यान्वयन "साझा" है। जैसा कि आप देख सकते हैं, बराबर (ऑब्जेक्ट) के अंत में बराबर (MyClass) के लिए एक कॉल है। मुझे उत्परिवर्तन और GetHashCode() मुद्दों के बारे में पता है; लेकिन यह एक महत्वपूर्ण अवलोकन है। यह मुझे कई बार थोड़ा सा है। बहुत बुरा है कि केवल "कक्षाएं" पढ़ने की घोषणा करने का कोई "आसान" तरीका नहीं है। –
लिंक अभी के लिए टूट गया है। – Restuta