我正在尝试使用C#,我构建了以下程序(见下文).
我明白动态和静态类型first
是C
.对于second
动态类型也是C
静态类型A
.现在我想知道这可能会派上用场吗?
我也注意到(显然)视觉工作室不允许我打电话second.CallA()
.
现在请注意,当我在所有三种类型的静态类型上调用DoA()时,动态类型是C
.在这种情况下,为什么不this
指向那个班级呢?如果我在Java中记得正确(我可能会误会),那么self.methodA()
就会开始从调用者实例查找inhertence树.因为它似乎不像这里.我可以创建这样的行为,还是这种语言的限制?
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();
}
Run Code Online (Sandbox Code Playgroud)
输出:
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!
Run Code Online (Sandbox Code Playgroud)
我可以创建这样的行为,还是这种语言的限制?
您可以创建此类行为.为此,您需要将方法设为虚拟.这将为您提供该行为,而不使用动态.
public class A
{
public virtual void methodA()
{
Console.WriteLine("I am class A!");
}
Run Code Online (Sandbox Code Playgroud)
然后,后来:
public class B : A
{
public override void methodA()
{
Console.WriteLine("I am class B!");
}
}
Run Code Online (Sandbox Code Playgroud)
在C#中,您必须明确地使您的方法成为虚拟.在Java中,默认情况下,方法实际上是虚拟的.这不是语言的限制 - 它只是两种语言之间的差异.