繁体   English   中英

动态类型和静态类型C#

[英]Dynamic type and static type C#

我正在试验C#,并构建了以下程序(请参见下文)。

我知道first的动态和静态类型是C second ,动态类型也是C而静态类型是A 现在,我想知道这可能会派上用场吗?

我也很明显地注意到Visual Studio不允许我调用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!

我可以创造这种行为吗?或者这是语言的限制吗?

您可以创建这种行为。 为此,您需要使您的方法虚拟化。 这将为您提供这种行为,而根本不用动态。

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中,默认情况下方法实际上是虚拟的。 这不是语言的限制-只是两种语言之间的差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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