c# - from enum to generic type -
this question has answer here:
- how use reflection call generic method? 7 answers
i have 2 class this
public class excel: document{ } public class pdf: document{ } and base class document.
i have enum
public enum documenttype{ excel = 1, pdf = 2 } i have core class generic method implemented method
public class manager{ loadfile<t> (stream stream) t: document{ ... } } can call loadfile method command this
type gettype(documenttype documenttype){ ... } loadfile<gettype(documenttype.excel)>(mystream){ ... } i want have generic parameter created enum.
the error
< generic cannot applied operands of type 'method group'
for cases know type @ compile time, such "please load pdf, it's going pdf" - don't see reason @ generics @ all. you're not saving time on instantiating object stream data, , letting build itself.
// example class pdf : document { public pdf(stream stream) { // load pdf data stream here } } for cases don't know object type, "load file user selected, might pdf, might excel file", don't want worrying generics. instead, want function returns base document type - don't know type before loading (i.e. @ compile time, don't know - can't use generics):
document loadfromstream(stream stream) { var typeofdocument = somemethodtofindthefiletypefromthestream(stream); switch(typeofdocument) { case documenttype.pdf: return loadpdffromstream(stream); // returns pdf object case documenttype.excel: return loadexcelfromstream(stream); // returns excel object default: throw new exception("document not supported type"); } } if need specific object, you'll need downcast using information within object (such document type enum) figure out type cast to.
there no silver-bullet generic solution i'm afraid. if know file type @ compile time, generics aren't saving anything. if don't - need conditional logic determine type (whether before or after loading, e.g. using file extension decide).
generics won't save time or make life easier here @ all.
Comments
Post a Comment