C# generics is keyword covariance / contravariance type inferral -
please consider interface:
public interface iinitialiazableentity<trepository> trepository : class, irepository { void initialize(trepository repository); }
this class (snippet):
public class somefacade<trepository> trepository : class, irepository { public void add<tentity>(tentity entity) tentity : abstractentity { seek { if (entity iinitialiazableentity<trepository>) (entity iinitialiazableentity<trepository>).initialize(this.repository); } grab (exception ex) { this.logger.error(ex); } } }
and entity:
public class pupil : abstractentity, iinitialiazableentity<irepository> { void initialize(irepository repository) { ... } }
since pupil iinitialiazableentity<irepository>
, facade have actual repository more specialized basic irepository
(i.e. imyspecialrepository : irepository
), is
keyword realize can cast imyspecialrepository
, pass initialize
method of entity? or if not, how it?
currently, if had instance somefacade<imyspecialrepository>
code not work.
you have 2 options, 1 reply provided dan bryant, other create iinitialiazableentity<trepository>
contravariant.
your interface declaration become (note in
on generic type):
public interface iinitialiazableentity<in trepository> trepository : class, irepository { void initialize(trepository repository); }
this allow is
check , cast work, iinitialiazableentity<irepository>
can cast iinitialiazableentity<imyspecialrepository>
when using contravariant generic.
see here more info covariance , contravariance in generics.
c# generics covariance contravariance
No comments:
Post a Comment