Implementation of custom equals Methods

Source: Internet
Author: User

If we want to create a class, whether it is a reference or a value type, we often need to implement the equals method. The following two general implementation methods are written here

1. Implementation of the reference type

 

Class MyRefType: BaseType {
RefType refobj; // reference type object
ValType valobj; // value type object
Public override bool Equals (object obj)
{
// When the base class implements equals, first call the equals method of the base class and then perform other operations. If the base class does not override the equals method, this judgment can be removed.
If (! Base. Equals (obj) return false;
// Because this cannot be null, if obj is null, it cannot be equal.
If (obj = null ){
Return false;
}
// If the two objects have different types, they cannot be equal.
If (this. GetType ()! = Obj. GetType () return false;
//
MyRefType other = (MyRefType) obj;
If (! Object. equals (refobj, other. refobj) return false; // any type of variable in the reference type can be determined using the static equals method of the object, however, the equals method of the value type class is different here and can be used for reference, but the value type variable changes.
If (! Object. Equals (valobj, other. valobj) return false;
Return true;
}
// When the equals method is rewritten, it must be "=" and "! = "To rewrite
Public static Boolean operator = (MyRefType o1, MyRefType o2 ){
Return object. Equals (o1, o2 );
}
Public static Boolean operator! = (MyRefType o1, MyRefType o2 ){
Return
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.