Convert object to generic object in C# -
i have list of generic objects:
private readonly list<object> _repositories = new list<object>();
those object of type either "xmlrepository<t>" or "dbrepository<t>". have generic methods returns me first repository of generic type argument provided:
public irepository<t> getrepository<t>() t : class {...}
i know type argument should return xmlrepository<t> or dbrepository<t>:
var xmltypevar = typeof(xmltype); var myxmlrepo = getrepository<xmltypevar>()
but don't know how convert correctly typed object instance...
var myconvertedxmlrepo = myxmlrepo xmlrepository<???>
what have here? following not possible:
var myconvertedxmlrepo = myxmlrepo xmlrepository<xmltypevar>since i'm not allowed provide variable generic type argument... example here somehow simplicated, not possible me replace type variable (xmltypevar) dedicated type itself.
any highly appreciated! thank much!
use reflection create generic type without knowing @ compile time:
type genericxmlrepositorytype= typeof(xmlrepository<>); type[] typeargs = new[] { xmltypevar }; var generic = genericxmlrepositorytype.makegenerictype(typeargs);
as written in comments, if want access method of xmlrepository<> after creating dynamic instance, best idea create non-generic base class , call method there:
xmlrepository repository = (xmlrepository)generic; repository.usetypespecificmethod();
Comments
Post a Comment