[Mono-list] An inheritance dilemma
Abe Gillespie
abe.gillespie at gmail.com
Sun Nov 21 13:53:43 EST 2010
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";
}
}
}
On Sun, Nov 21, 2010 at 1:49 PM, Abe Gillespie <abe.gillespie at gmail.com> wrote:
> Don't call base in SampleMethod -> this skips your override /
> virtualization. SampleMethod should be:
>
> public override void SampleMethod () {
> SampleMethod();
> Console.WriteLine (this.BuildString());
> }
>
> Note that you can also do:
>
> A a = new B();
> a.SampleMethod();
>
> and you'll get B's implementation of SampleMethod.
>
> Good luck.
> -Abe
>
> On Sun, Nov 21, 2010 at 1:13 PM, Francisco M. Marzoa <fmmarzoa at gmx.net> wrote:
>> Hello,
>>
>> I'll start by the code, because I think it's the best way of
>> illustrating the problem in this case:
>>
>> using System;
>>
>> 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";
>> }
>>
>> protected string BuildString () {
>> return this.GetClassName() + " method";
>> }
>>
>> public virtual void SampleMethod () {
>> Console.WriteLine (this.BuildString());
>> }
>> }
>>
>> public class B : A {
>> protected override string GetClassName() {
>> return "Class B";
>> }
>>
>> public override void SampleMethod () {
>> base.SampleMethod();
>> Console.WriteLine (this.BuildString());
>> }
>> }
>>
>> }
>>
>>
>> The output of this code is:
>>
>> Class B method
>> Class B method
>>
>> While what I want to get is:
>>
>> Class A method
>> Class B method
>>
>> I've tried with some minor changes, like removing "virtual" and
>> "override" from GetClassName, getting:
>>
>> Class A method
>> Class A method
>>
>> But I didn't been able to get the output that I want. Perhaps using
>> reflection???
>>
>>
>> _______________________________________________
>> Mono-list maillist - Mono-list at lists.ximian.com
>> http://lists.ximian.com/mailman/listinfo/mono-list
>>
>
More information about the Mono-list
mailing list