簡體   English   中英

使用override和new關鍵字覆蓋ToString()

[英]override ToString() with override and new keyword

我是c#.confuse中的新手。

我用覆蓋覆蓋了ToString(),新的keyword.both給了我相同的輸出。然后兩者之間有什么區別。

這是我的例子

class A
{
    public new string ToString()
    {
        return "With New Keyword";
    }
}
class B
{
    public override string ToString()
    {
        return "With Override Keyword";
    }
}


class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();

        Console.WriteLine(a.ToString());
        Console.WriteLine(b.ToString());

        Console.Read();
    }

}

產量

使用新關鍵字

使用覆蓋關鍵字

我知道這是一個愚蠢的問題。 請任何人幫我兩個方法給我區別。

我不是在詢問new和override關鍵字之間的區別。我想知道兩種方法之間的區別。在Override Object方法的概念中。

當你這樣做時,它會有所不同:

object a = new A(); // notice the type of the variable here!
object b = new B();
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());

a.ToString()不會調用ToString的實現,而是調用object.ToString ,它返回對象的完全限定類型名稱。 b.ToString() 調用您的實現。

你在B所做的被稱為覆蓋。 你在A所做A就是隱藏 當變量的編譯時類型不再是該類型時,隱藏會失去效果。 只有在編譯時類型為A時才會調用ToString實現。

在這里了解更多。

你可以輕松谷歌這個。

來自MSDN

在C#中,派生類中的方法可以與基類中的方法具有相同的名稱。 您可以使用new和override關鍵字指定方法的交互方式。 override修飾符擴展基類方法,new修飾符隱藏它。 本主題中的示例說明了這種差異。

在控制台應用程序中,聲明以下兩個類,BaseClass和DerivedClass。 DerivedClass繼承自BaseClass。

B類中,您將覆蓋ToString()方法,即Object.ToString()因為您沒有繼承A 現在考慮下面的例子,

class A
{
    public string ReturnString()
    {
       return "ClassA::Method";
    }
}
class B : A
{
    public newstring ReturnString()
    {
        return "ClassB::Method";
    }
}


class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();

        Console.WriteLine(a.ToString());
        Console.WriteLine(b.ToString());

        Console.Read();
    }
}

在這里,您將繼承Class A class B的方法隱藏在class B Class A 因此,您將獲得兩個方法調用的ClassA::Method輸出。

現在考慮下面的例子

class A
{
    public virtual string ReturnString()
    {
       return "ClassA::Method";
    }
}
class B : A
{
    public override string ReturnString()
    {
        return "ClassB::Method";
    }
}


class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();

        Console.WriteLine(a.ToString());
        Console.WriteLine(b.ToString());

        Console.Read();
    }
}

在這里,我們重寫了Class B Class A's Class B方法。 這意味着ClassB method就像擴展一樣,或者你可以說它與ClassA有不同的含義。 您將獲得如下輸出

ClassA::Method
ClassB::Method

暫無
暫無

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

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