[Mono-list] An inheritance dilemma

Francisco M. Marzoa fmmarzoa at gmx.net
Mon Nov 22 09:09:39 EST 2010


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