簡體   English   中英

在C#中,如果某個類或方法沒有標記為密封或虛擬,那么它是什么?

[英]In C#, if a class or a method is not marked as sealed or virtual, what is it?

換句話說,什么是默認值(如果沒有指定)? 我猜測默認是虛擬的,因為即使基本方法沒有指定虛擬,你也可以使用“new”關鍵字覆蓋基本方法。 如果是這樣的話,為什么我們甚至需要虛擬選項? 當我們確實需要阻止進一步繼承時,我們難道不能使用Sealed嗎?

默認情況下密封C#方法 - 如果沒有virtual關鍵字,則無法覆蓋它們。

new關鍵字隱藏了基類中的方法。

這就是隱藏的意思:

public class HidingA
{
    public string Get()
    {
        return "A";
    }
}

public class HidingB : HidingA
{
    public new string Get()
    {
        return "B";
    }
}

HidingA a = new HidingA();
HidingB b = new HidingB();

Console.WriteLine(a.Get()); // "A"
Console.WriteLine(b.Get()); // "B"

HidingA c = new HidingB();
Console.WriteLine(c.Get()); // "A". Since we're calling this instance of "B" an "A",    
                            //we're using the "A" implementation.

現在,虛擬版!

public class VirtualA
{
    public virtual string Get()
    {
        return "A";
    }
}

public class VirtualB : VirtualA
{
    public override string Get()
    {
        return "B";
    }
}
VirtualA a = new VirtualA();
VirtualB b = new VirtualB();

Console.WriteLine(a.Get()); // "A"
Console.WriteLine(b.Get()); // "B"

VirtualA c = new VirtualB();
Console.WriteLine(c.Get()); // "B". We overrode VirtualB.Get, so it's using the 
                            // "B" implementation of the method

因此,如果我們創建一個將HidingA作為參數並將其傳遞給HidingB的實例的HidingB ,我們將獲得Get方法的HidingA實現。

MSDN: http//msdn.microsoft.com/en-us/library/6fawty39.aspx

除非指定了sealed關鍵字,否則將打開類繼承。

new創建一個新方法(不覆蓋它),其中被覆蓋的方法將替換它,因此是virtual 如上所述,DanielM默認密封方法。

這就是我們需要虛擬的原因:

   class Foo
   {
       public void Baz() { Assert("Foo.Baz"); }
   }

   class ChildOfFoo : Foo
   {
       public new void Baz() { Assert("ChildOfFoo.Baz"); }
   }

   Foo foo = new ChildOfFoo();
   foo.Baz(); // Foo.Baz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM