c# - Can you model an interface where only it's descendants can be implemented? -
assume following code:
namespace example { public interface ibase { string commonmember { get; set; } } public interface iderived : ibase { void dosomething(); } public interface icomplexderived : ibase { ienumerable<object> junk { get; } } }
i have similar structure in project i'm working on. interface ibase
serves purpose able keep instances of iderived
, icomplexderived
in same container (like list<ibase>
) , not having repeat common interface member definitions (like commonmember
in example).
one way used this:
public class foo { public void bar( ienumerable<ibase> instances ) { foreach( ibase instance in instances ) { if( instance iderived ) { /* */ } else if( instance icomplexderived ) { /* else */ } } } }
so, nothing stop user implementing ibase
, passing instances of class system. doing useless because whole library expects deal classes implement interfaces derived ibase
.
this concept of course documented , shouldn't cause problems. however, wondering if possible communicate through means of language itself. having abstract class, interfaces.
you might ask why not use abstract class then. reason don't want impose requirement inherit our class.
i'm not sure if feasible in actual case, think have
icomplexderived
inheritiderived
instead ofibase
.- you have list of
iderived
instead ofibase
, new implementation ofibase
not type-check (since requireienumerable<iderived>
) - your classes inheriting
icomplexderived
implementdosomething()
in different way. doing letbar
method decide polymorphically dosomething needs call (and avoid checking on type)
i mean this:
public interface ibase { string commonmember { get; set; } } public interface iderived : ibase { void dosomething(); } //icomplexderived isnow iderived public interface icomplexderived : iderived { ienumerable<object> junk { get; } } public class foo { // bar requires ienumerable<iderived> can't call collection // of classes implementing ibase public void bar( ienumerable<iderived> instances ) { foreach( iderived instance in instances ) { instance.dosomething(); // dosomething "do else" in // classes implementing icomplexderived } } }
Comments
Post a Comment