[Mono-list] An inheritance dilemma

Abe Gillespie abe.gillespie at gmail.com
Mon Nov 22 09:27:39 EST 2010


I've never run into a situation which required inheritance that I
could not get working with some combo of abstract, virtual, and
override.  We can only help you as detailed as your example is.  So
without a better description of the problem this is the best help we
can offer.

You most likely don't have to "settle" on a half-baked solution.  And
your example looks like a rather common use of inheritance.

Keep thinking about the problem until you find a solution that is 100%
satisfying.  That or take a little more time to send us a more
detailed problem description.

-Abe

On Mon, Nov 22, 2010 at 9:09 AM, Francisco M. Marzoa <fmmarzoa at gmx.net> wrote:
> Thanks a lot for your help, Abe.
>
> The previous code was just a simplified version of a more complex one.
> The fact is that I need each class to have it's own SampleMethod, so it
> cannot be just removed from B class. And that's the real root of the
> problem. Obviusly you couldn't know this.
>
> Anyway after look more into this, I've reached the conclussion that
> there's no chance to obtain the output I want with the class scheme I
> proposed without, perhaps, dirty hacks based on reflection. And prior
> doing that, I think it's better to rethink the scheme.
>
> So, the best solution I've found is to rewrite both classes like follows:
>
>    public class A
>    {
>        protected string BuildString( string cname )
>        {
>            return cname + " method";
>        }
>
>        public virtual void SampleMethod()
>        {
>            Console.WriteLine(this.BuildString("Class A"));
>        }
>    }
>
>    public class B : A
>    {
>        public override void SampleMethod()
>        {
>            base.SampleMethod();
>            Console.WriteLine(this.BuildString("Class B"));
>        }
>    }
>
>
>
> The key point on this is that as there should be a different
> SampleMethod overrided in each descendant, we do know within that method
> the class we're executing in, so we can pass it from there instead of
> use an instance method GetClassName.
>
> Best regards,
>
>
> El 21/11/10 19:53, Abe Gillespie escribió:
>> I just realized you *really* doing virtualization in GetClassName().
>> So the better way to do this is:
>>
>> namespace Dummy
>> {
>>    class MainClass
>>    {
>>        public static void Main (string[] args)
>>        {
>>            B b = new B();
>>            b.SampleMethod();
>>        }
>>    }
>>
>>    public class A {
>>        protected virtual string GetClassName() {
>>            return "Class A";
>>        }
>>
>>        public void SampleMethod () {
>>            Console.WriteLine (GetClassName() + " method");
>>        }
>>    }
>>
>>    public class B : A {
>>        protected override string GetClassName() {
>>            return "Class B";
>>        }
>>    }
>> }
>>
>>
>
>


More information about the Mono-list mailing list