c# - Generic inherited methods -
c# - Generic inherited methods -
i have question generic inherited methods.
say illustration have have base of operations manager class listmanager:
public class listmanager<t> { private list<t> m_list; public listmanager() { m_list = new list<t>(); } public int count { { } } public void add(t atype) { } public bool deleteat(int anindex) { } public string[] tostringarray() { } public list<string> tostringlist() { } public bool checkindex(int index) { } }
and animal manager class inherits list manager class above:
public class animalmanager : listmanager<animal> { private list<animal> animallist; //list public animalmanager() { animallist = new list<animal>(); } public void add(animal animal) // same base of operations class method different method "content". { animal.id = ++animalcounter; //increases id one. animallist.add(animal); } public bool isindexvalid(int index) { homecoming ((index >= 0) && (index < animallist.count)); } public animal getelementatposition(int index) { if (isindexvalid(index)) homecoming animallist[index]; else homecoming null; } public int elementcount { { homecoming animallist.count; } } public bool deleteat(int anindex) { homecoming true; } }
what do methods inherit listmanager? needs inherited methods different "content" within method.
i know long class inherits class, inherit base of operations class has, do if every management class handles different listboxes has exact same method head.
for example, every manager class has add
:
public void add(t atype) { }
but animal manager needs add together animal list:
public void add(animal animal) { animallist.add(animal); }
and employee manager needs add together employeelist :
public void add(employee employee) { employeelist.add(employee); }
they have exactly same method different "content".
you create base of operations class methods virtual, , override them in derived class:
public class listmanager<t> { private list<t> m_list; public listmanager() { m_list = new list<t>(); } public virtual void add(t atype) { } } public class animalmanager : listmanager<animal> { private list<animal> animallist; //list private int animalcounter; //variable public animalmanager() { animallist = new list<animal>(); } public override void add(animal animal) { animal.id = ++animalcounter; //increases id one. animallist.add(animal); } } public class animal { public int id { get; set; } }
you may want extend existing list<t>
, if base of operations class isn't doing special:
public class animalmanager : list<animal> { private int animalcounter; public new void add(animal animal) { animal.id = ++animalcounter; base.add(animal); } }
c# generics inheritance
Comments
Post a Comment