c# - Can I use a generic method as a sort of template pattern? -



c# - Can I use a generic method as a sort of template pattern? -

hi i'm not sure generic method right way solve problem. need parse xml file , read items it. items can things orderlines, notes, attachments. basic steps these items same. how can create 1 method creates list of these items , phone call specific method read item?

public override ilist<t> getitems<t>(xpathnavigator currentorder) t : isortablebylinenumber, new () { var itemlist = new list<t>(); var itemxmlnodes = currentorder.select(orderxpath); if (itemxmlnodes == null) throw new exception(""); var linenumber = 1; foreach (xpathnavigator itemxmlnode in itemxmlnodes) { var item = new t(); item = readitem(itemxmlnode, linenumber++, item); itemlist.add(item); logger.debug(string.format("added item {0}", item)); } homecoming itemlist; }

i thought readitem method. create overloads each type of item reading.

private isortablebylinenumber readitem(xpathnavigator itemxmlnode, int i, orderline item) { // specific code read orderline } private isortablebylinenumber readitem(xpathnavigator itemxmlnode, int i, note item) { // specific code read note }

but when seek compile "the best overloaded method match 'xmlorderparser.xmlorders.prs3xmlfilewithorders.readitem(system.xml.xpath.xpathnavigator, int, xmlorderparser.entities.orderline)' has invalid arguments". problem compiler doesn't know how cast t orderline or note.

if using .net 4 can create utilize of new dynamic type changing 1 thing:

dynamic item = new t(); // instead of var item = new t();

because item dynamic runtime automatic overload resolution based on actual type of item. please aware receive runtime exception if t type no overload exists.

the next snippet demonstrates problem (paste linqpad , take "c# program" language):

void main() { method<class1>(); // outputs class1 method<class2>(); // outputs class2 method<class2b>(); // outputs class2, because falls base of operations type method<class3>(); // throws exception } void method<t>() t : new() { dynamic c = new t(); method(c); } void method(class1 c) { console.writeline("class1"); } void method(class2 c) { console.writeline("class2"); } class class1 {} class class2 {} class class2b : class2 {} class class3 {}

c# .net generics design-patterns

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -