say have non generic base interface, generic inheriting interface:
public interface ifoo { } public interface ibar<t, k> : ifoo { k do(t t); } public class barimpl : ibar<type, anothertype> { public anothertype do(type type) { return new anothertype(type); } } i need create factory returns ifoo instance, using returned instance need able call derived types do(t), isn't available.
public class foofactory() { ifoo get() { // simplified, in reality returning correct // type checking generic interface // types object stored list // of implementations return barimpl(); } } // in class public void dofoo() { ifoo ifoo = new foofactory().get(); // need able call ifoo.do(type) cannot } the way have been able work create dynamic object, instead of ifoo, , call do() - work in case lose type safety i'd prefer keep.
my question can re-engineer able access derived interfaces method, whilst still being able maintain list (and subsequently factory method return type) of ifoo????
you expect or want type safety, think way:
- in order able call
do,getneeds return type defines method.ifoonot have it,ibar<t, k>does.getreturnsifooobject not guaranteedibar<t, k>. - even if implementation of
getmake sureibar<t, k>returned, there no way type system know without returning type. - assuming return type allowed call
domethod, type unclear: need pass object of typet. returnedifoooribar<t, k>not use same typetwanted passdo. - even if implementation of
getprovide (like “get meibar<t, k>accepts typet”) , type system have way reflect this, still wouldn’tk. knownt, stillibar<t, int>, oribar<t, string>. , there no way know without having concrete type. - and still, assuming work type system: purpose serve? call method of generic type correct typed argument: return value still has no concrete type. couldn’t returned type
do.
my point need generic types, when have reason maintain concrete type. if call generic method or method of generic type non-generic method, either have discrete set of types you’re working with, or don’t need generic type information.
so maybe you’re better off introducing non-generic ibar type here:
interface ibar { object do(object t); } interface ibar<t, k> : ibar { k do(t t); } public class barimpl : ibar<type, anothertype> { public anothertype do(type type) { return new anothertype(type); } public object do(object t) { return do((type) t); } } then make get return ibar instead, , have way call do.
btw. pattern used pretty commonly in bcl, e.g. ienumerable<t> , ienumerable.
Comments
Post a Comment