c# - How do I customize List<T>? -
this question exact duplicate of:
i trying customize list. have figured out coming across problem. here code working with:
public class myt { public int id { get; set; } public myt set(string line) { int x = 0; this.id = convert.toint32(line); return this; } } public class mylist<t> : list<t> t : myt, new() { internal t add(t n) { read(); add(n); return n; } internal mylist<t> read() { clear(); streamreader sr = new streamreader(@"../../files/" + gettype().name + ".txt"); while (!sr.endofstream) add(new t().set(sr.readline())); //<----here error! sr.close(); return this; } } public class customer : myt { public int id { get; set; } public string firstname { get; set; } public string lastname { get; set; } } public class item : myt { 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>(); } in code, can see trying create customize list. here see 2 of many classes have. of classes have id. of classes matched custom list. problem seems in mylist<t>.read() - add(new t().set(sr.readline())); lastly, myt can not converted t. need know how fix it.
the set method returns type myt instead of specific type. make generic can return specific type:
public t set<t>(string line) t : myt { int x = 0; this.id = convert.toint32(line); return (t)this; } usage:
add(new t().set<t>(sr.readline())); or cast reference specific type:
add((t)(new t().set(sr.readline())));
Comments
Post a Comment