(C #, VS2008). In the program I'm working on, I have many objects that have an identifier and an IComparable implementation, so List <> - s of different objects can be easily found by identifier. Since I hate copy / paste code, I thought I would drop this functionality to the base class, for example:
using System; namespace MyProg.Logic { abstract class IDObject : IComparable<IDObject> { private int miID; public int ID { get { return miID; } set { miID = value; } } public IDObject(int ID) { miID = ID; } #region IComparable<IDObject> Members int IComparable<IDObject>.CompareTo(IDObject other) { return miID.CompareTo(other.miID); } #endregion } }
The drawback that I see in this is that two separate classes, each of which inherits it, will be directly comparable using .CompareTo (), and I was hoping to ensure that every class that inherits IDObject compares only with the others from the same class, so I was hoping to figure out how to do this, and came up with this
using System; namespace MyProg.Logic { abstract class IDObject : IComparable<T> where T : IDObject { private int miID; public int ID { get { return miID; } set { miID = value; } } public IDObject(int ID) { miID = ID; } #region IComparable<T> Members int IComparable<T>.CompareTo(T other) { return miID.CompareTo(other.miID); } #endregion } }
But this gives a compilation error "Restrictions are not allowed for non-generic declarations"
Looking at this, I am sure there is a way to do something like this so that each class is comparable to other instances of the same class, but I cannot separate the syntax.
Drogo
source share