动态类型和静态类型C#

时间:2014-01-03 20:51:02

标签: c# inheritance

我正在尝试使用C#,我构建了以下程序(见下文)。

我了解first的动态和静态类型为C。对于second,动态类型也是C,但静态类型为A。现在我想知道这可能会派上用场吗?

我也注意到(显然)视觉工作室不允许我拨打second.CallA()

现在请注意,当我在所有三种类型的静态类型上调用DoA()时,动态类型为C。在这种情况下,为什么this没有指向那个类?如果我在Java中记得正确(我可能会误会),self.methodA()将开始从调用者实例中查找入侵树。因为它似乎不像这里。我可以创建这样的行为,还是这种语言的限制?

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();
    }

输出:

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!

1 个答案:

答案 0 :(得分:6)

  

我可以创建此类行为,还是这种语言的限制?

您可以创建此类行为。为此,您需要将方法设为虚拟。这将为您提供该行为,而不使用动态。

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

然后,后来:

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

在C#中,您必须明确地将您的方法设为虚拟。在Java中,默认情况下,方法实际上是虚拟的。这不是语言的限制 - 这只是两种语言之间的差异。