.net - Implementing IEquatable in a base class and use it in all the derived classes -
i have base class implements iequatable interface:
public mustinherit class daobase : implements iequatable(of daobase) mustoverride function getprimarykey() integer shadows function equals(other daobase) boolean implements iequatable(of daobase).equals return getprimarykey() = other.getprimarykey end function overrides function gethashcode() integer return getprimarykey() end function ' more things here end class all subclasses must provide getprimarykey method.
public class packaging inherits daobase public sub new(id integer) me.id = id end sub overrides function getprimarykey() integer return id end function <daofield> property id integer end class list(of packaging).contains never calls equals method expected.
dim packs new list(of packaging)() dim pack new pack(1) dim pack2 new pack(1) packs.add(pack) now, packs.contains(pack) <- true, ok, reference equality
but, packs.contains(pack2) <- false, nok!
i don't want "remember" implement iequatable in derived classes.
is there way force derived implement iequatable, or, better, make contains call base class daobase.equals?
the solution i've found generic-ize base class:
public mustinherit class daobase(of t) : implements iequatable(of t) mustoverride shadows function equals(other t) boolean implements iequatable(of t).equals mustoverride overrides function gethashcode() integer end class public class packaging inherits daobase(of packaging) public sub new(id integer) me.id = id end sub overrides function equals(other packaging) boolean return gethashcode() = other.gethashcode() end function overrides function gethashcode() integer return id end function property id integer end class now equals must overridden , specialized on derived type.
dim p1 new packaging(1) dim p2 new packaging(1) dim packs new list(of packaging) packs.add(c1) debug.print(packs.contains(c1)) <- true debug.print(packs.contains(c2)) <- true but have write many identical equals methods in derived classes. looking way avoid this.
Comments
Post a Comment