简体   繁体   中英

Dynamic type and static type C#

I'm experimenting with C# and I built the following program (see below).

I understand that the dynamic and static type of first is C . For second the dynamic type is also C but the static type is A . Now I wonder where this might come in handy?

I noticed as well (obviously) that visual studio doesn't allow me to call second.CallA() .

Now notice that when I call DoA() on all three types of static type, the dynamic type is C . As this is the case, why doesn't this point to that class? If i recall correct (I might be mistaking) in Java a self.methodA() would start looking up the inhertence tree from the caller instance. As it doesn't appear to be like that here. Can I create such behavior or is this a limitation of the language?

public class A
{
    public void methodA()
    {
        Console.WriteLine("I am class A!");
    }
    public void DoA()
    {
        Console.Write("The type of this: " + this.GetType() + " - ");
        this.methodA();
    }
}
public class B : A
{
    public void methodA()
    {
        Console.WriteLine("I am class B!");
    }
}
public class C : B
{
    public void methodA()
    {
        Console.WriteLine("I am class C!");
    }
}


class Program
{
    static void Main(string[] args)
    {
        C first = new C();
        A second = new C();
        dynamic third = new C();

        //Show the types of both

        Console.WriteLine(first.GetType() + "\n" + second.GetType() + "\n" + third.GetType());
        first.methodA();
        second.methodA();
        third.methodA();

        first.DoA();
        second.DoA();
        third.DoA();



        Console.ReadLine();
    }

Output:

C
C
C
I am class C!
I am class A!
I am class C!
The type of this: C - I am class A!
The type of this: C - I am class A!
The type of this: C - I am class A!

Can I create such behavior or is this a limitation of the language?

You can create such behavior. In order to do so, you need to make your methods virtual. This will give you that behavior, without using dynamic at all.

public class A
{
    public virtual void methodA()
    {
        Console.WriteLine("I am class A!");
    }

Then, later:

public class B : A
{
    public override void methodA()
    {
        Console.WriteLine("I am class B!");
    }
}

In C#, you must explicitly make your methods virtual. In Java, methods are effectively virtual by default. This isn't a limitation of the language - it's just a difference between the two languages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM