c# - Creating instance of a generic type from a instance of the type parameter -
i have bl consisting of generic repository , specific implementations couple of entity types (my dal entity framework 5 model). repository uses it's functionality method set() of system.data.entity.dbcontext. have expressions things getting siblings of entity t, these won't work on result of set(type entitytype).
at 1 moment have instance of non-generic dbentityentry. entity of type object. when use gettype() approptiate entity type. know want related entity using functions in repository. there way non-generic dbentityentry.
i tried:
public repository(t entity) { \\ construction here }
but repository<object>
, call set<object>
returns nothing expected.
i've searched way came empty.
take @ example posted george mauer in this thread. requires .net 4.0 or higher.
dynamic dynamiccast(object entity, type to) { var opencast = this.gettype().getmethod("cast", bindingflags.static | bindingflags.nonpublic); var closecast = opencast.makegenericmethod(to); return closecast.invoke(entity, new[] { entity }); } static t cast<t>(object entity) t : object { return entity t; }
you can use modified variant of create matching repository
instance:
public static dynamic createrepository(object entiry, type targettype) { type basetype = typeof(repository<>); type concretetype = basetype.makegenerictype(targettype); var instance = activator.createinstance(concretetype, entiry); return dynamiccast(instance, concretetype); }
Comments
Post a Comment