c# - Accessing derived class properties when implementing an interface method with abstract base class as parameter -
i tried hard find answer question, if has been asked already, perhaps i'm wording wrong. have abstract base class , derived class.
abstract class foo { protected int property1 protected int property2 // etc.. }
my dervied class contains properties not found in base class:
class fum : foo { public int uniqueproperty { get; set; } }
now have interface method takes abstract base class:
interface idosomethingwithfoos { void dosomethingwithfoo(foo fooey); }
a class implements interface
class fumlover : idosomethingwithfoos { void dosomethingwithfoo(foo fooey) { // in here know going passed objects of fum // , want access unique properties fooey.uniqueproperty = 1; // doesn't work ((fum)fooey).uniqueproperty = 1; // seems work // does.. fum reftofum = fooey fum; reftofum.uniqueproperty = 1; } }
so question is: going in right way? although compiles, don't have enough code in place make sure yet going work properly. , other question is: bad design? there better way?
*
to elaborate little more, because natural response is, if going passing fum, have interface method take fum instead of foo.
but let's in fumlover class, method dosomethingwithfoo deals 95% properties in abstract bass class. , let's have derived class called fie, has couple of unique properties. let's have fielover class, , want implement dosomethingwithfoo because 95% of i'm going here apply foo, again, there little bit unique fie.
what alternative? have interface each one: idosomethingwithfums, idosomethingwithfies, etc.? seems lose abstraction 5% of difference.
// in here know going passed objects of fum // , want access unique properties
this clue design change might help. current interface says "i work on foo
s". if implementation works on fum
s, you've got mismatch in you're saying , you're doing. if you're expecting fum
s, declare parameter in interface fum
.
if don't want that, using as
syntax preferable, since don't throw exception when thinks can pass in foo
(since hey, interface says can.)
the as
code should this:
fum fumobj = fooey fum; if (fumobj != null) fumobj.uniqueproperty = 1;
update:
your suggestion of interface each derived class preferable (since do,) let's take step back: trying accomplish here? if want idosomethingwithfoos
take advantage of foo
's place base class (albeit abstract one,) need ensure calling dosomethingwithfoo
meaningful foo
s. if not, you've lost, since though claim foolover, love fum
s (or fie
s.)
one solution declare abstract dosomething()
method on foo
itself. now, have list<foo>
, , have code this:
foreach (foo foo in foolist) foo.dosomething();
now you're taking advantage of abstraction. don't care kind of foo
s are: something, possibly based on properties unique derived class (no casting required.)
Comments
Post a Comment