I have series of classes that are implementing CompareTo
method from IComparable
interface.
public int CompareTo(CMNewsletter obj)
{
CMNewsletter c = obj;
return String.Compare(c.Name, this.Name);
}
Each class has it's own CompareTo
implementation. So the implementation should be done in each class.
Now there is a need to call CompareTo on some base class objects. CMBase
is a base class class for all before mentioned classes.
The following code is how I want to design my classes.
CMBase reference, copy;
if (reference.CompareTo(copy) == 0)
{
Console.WriteLine("Not changed");
}
reference
and copy
objects will be of type CMNewsletter
or other, where the actual implementation of CompareTo
is residing.
I'm not sure how to implement whole class hierarchy to accomplish what I described.
First off you need to Implement IEquatable
and not IComparable
. Then you introduce two helper method namely EqualsHelper
and EqualsCore
to get the job done.
EqualsHelper
is just a helper method to find if equality fails and EqualsCore
is virtual, which you need to override in all derived classes and implement its equality there, nothing else.
class MyBase : IEquatable<MyBase>
{
public bool Equals(MyBase other)
{
return EqualsHelper(other);
}
public override bool Equals(object obj)
{
return EqualsHelper(obj as MyBase);
}
protected bool EqualsHelper(MyBase other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (other.GetType() != this.GetType()) return false;
return EqualsCore(other);
}
protected virtual bool EqualsCore(MyBase other)
{
return BaseProperty == other.BaseProperty;
}
public override int GetHashCode()
{
return BaseProperty;
}
public int BaseProperty { get; set; }
}
class Derived : MyBase, IEquatable<Derived>
{
public int DerivedProperty { get; set; }
public bool Equals(Derived other)
{
return EqualsHelper(other);
}
protected override bool EqualsCore(MyBase other)
{
Derived obj = (Derived)other;
return base.EqualsCore(obj) &&
this.DerivedProperty == obj.DerivedProperty;
}
}
I would make CMBase abstract class implementing IComparable interface as abstract method:
public abstract class CMBase : IComparable
{
public abstract int CompareTo(object o);
}
This will make all derived classes implement the CompareTo method. If you can't make this class abstract, then you can make implementation virtual which just throws exception, or if acceptable - implement some default comparison logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.