Creating and using a custom List<T> in C# -
i trying use customized list have added few additional tools. want apply list long list of customized classes have created. of classes have id number , of tools in list use id.
here portion of code trying use. hope understand problem.
namespace simple_point_of _sales_system { public class mylist<t> : list<t> { internal int setid() { return this.max(n => n.id) + 1; } internal t find(int id) { return this.find(n => n.id == id); } internal t add(t n) { read(); add(n); write(); return n; } internal void remove(int id) { read(); if (this.exists(t => t.id == id)) removeall(t => t.id == id); else messagebox.show(gettype().name + " " + id + " not exist.", "missing item", messageboxbuttons.ok, messageboxicon.error); write(); } internal void edit(int id, t n) { read(); if (this.exists(t => t.id == id)) this[findindex(t => t.id == id)] = n; else messagebox.show(gettype().name + " " + id + " not exist.", "missing item", messageboxbuttons.ok, messageboxicon.error); write(); } internal mylist<t> read() { clear(); streamreader sr = new streamreader(@"../../files/" + gettype().name + ".txt"); while (!sr.endofstream) add(new t().set(sr.readline())); sr.close(); return this; } internal void write() { streamwriter sw = new streamwriter(@"../../files/" + gettype().name + ".txt"); foreach (t n in this) sw.writeline(n.tostring()); sw.close(); } } public class customer { public int id; public string firstname; public string lastname; } public class item { public int id { get; set; } public string category { get; set; } public string name { get; set; } public double price { get; set; } } public class myclass { mylist<customer> customers = new mylist<customer>(); mylist<item> items = new mylist<item>(); } }
i think custom list needs put on constraints on generic type allow that. update signature like
public class mylist<t> : list<t> t : iidentity { .... }
here used iidentity
interface defining id
, class.
to update code this:
public interface iidentity { int id { get; } } public class customer : iidentity { public int id { get; set;} public string firstname; public string lastname; } public class item : iidentity { public int id { get; set; } public string category { get; set; } public string name { get; set; } public double price { get; set; } }
i changed id in customer
property instead of instance variable.
Comments
Post a Comment