[英]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.