簡體   English   中英

c#從派生類繼承或使用接口

[英]c# Inherit from derived class or use an interface

在C#中是否可以從派生類繼承? 例如,我具有以下結構,用C#合法嗎? 它可以編譯,但是我想知道這是否會在以后導致問題並在某些情況下引發錯誤。

public class A   
{
    public string s1 { get; set; }
    public string s2  { get; set; }
}

public class B : A   
{
    public string s3 { get; set; }
    public string s4 { get; set; }
}

public class C : B   
{
    public C()
    {
        this.S1 = "A prop";
        this.S2 = "A prop";
        this.S3 = "B prop";
        this.S4 = "B prop";
    }

    public string s5 { get; set; }
    public string s6 { get; set; }
}

我也可以使用接口,但據我了解,接口只是對實現該接口的任何事物強制執行合同。 因此,我仍然需要在派生類中實現所有屬性。 我想這不比這更多的代碼,所以也許這是執行此操作的正確方法? 在這種情況下,我認為C實現IA和IB只是意味着C必須實現屬性s1,s2,s3和s4。 那是對的嗎? 如果是這樣,這是否是更好的方法? 如果我在兩種情況下都離開,請告訴我。 謝謝

interface IA   
{
    string s1 { get; set; }
    string s2  { get; set; }
}

interface  IB : IA   
{
    string s3 { get; set; }
    string s4  { get; set; }
}

public class C : IA, IB   
{
    public C()
    {
        this.S1 = "A prop";
        this.S2 = "A prop";
        this.S3 = "B prop";
        this.S4 = "B prop";
    }

    public string s1 { get; set; }
    public string s2 { get; set; }
    public string s3 { get; set; }
    public string s4 { get; set; }
    public string s5 { get; set; }
    public string s6 { get; set; }
}

這是完全合法的,並且可能非常有用。 查看Button的繼承樹:

如果需要在類之間提供通用功能,則基類通常是最好的方法。

在C#中是否可以從派生類繼承?

如果稍微了解一下C#及其功能,您會發現C#是一種完全面向對象的編程語言,因此答案顯而易見: yes

另一方面,具有認真的編譯器的認真的編程語言不會讓您做回事 如果可以編譯,則從語法角度來看是有效的(它可能會在運行時崩潰,但存儲類型為storng的編譯語言將不允許您在設計時派生類,而在運行時崩潰...)。

關於界面...

接口不適合模擬繼承。 它們是合同,其用例可確保實現者需要為接口成員提供實現。 此外,接口支持繼承,但這是為了基於其他協議創建更廣泛的合同。

您還有另一種選擇〜將A類和B類抽象化。 如果您不希望有A和B的實例,請使其成為抽象或接口。

暫無
暫無

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

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