filehelpers - Create FileHelperEngine from Type variable -
i attempting create instance of filehelperengine<> using generic type. example works list
public static ilist createlist(type type) { var genericlisttype = typeof(list<>).makegenerictype(type); return (ilist)activator.createinstance(genericlisttype); }
is possible similar filehelperengine<>?
i tried
public static filehelperengine createfilehelperengine(type type) { var genericfilehelperenginetype = typeof (filehelperengine<>).makegenerictype(type); return (filehelperengine)activator.createinstance(genericfilehelperenginetype); }
and error
unable cast object of type 'filehelpers.filehelperengine`1[nachaparser.model.entrydetail.ppdentrymodel]' type 'filehelpers.filehelperengine'.
this not work because attempting go generic engine standard engine. generic engine not inherit standard engine can't directly cast.
the following code should work you:
public static filehelperengine<t> createfilehelperengine<t>() t : class { var genericfilehelperenginetype = typeof(filehelperengine<>).makegenerictype(typeof(t)); return (filehelperengine<t>)activator.createinstance(genericfilehelperenginetype); }
the problem need have type of t not type variable as passed generic argument. unfortunately, generic engine based of enginebase<t>
ifilehelperengine<t>
interface implements can never filehelperengine<t>
filehelperengine
.
your other option use:
public static filehelperengine createfilehelperengine(type type) { if (!type.isclass) throw new invalidcastexception("cannot use '" + type.fullname + "' not class"); return new filehelperengine(type); }
Comments
Post a Comment