簡體   English   中英

在派生類的基類中設置默認屬性

[英]Set default properties in base class from derived class

好的,我遇到了一個有趣且可能很簡單的問題。 我有一個由另一個類(子級)繼承的基類。 我在基礎和孩子中有相同的無參數構造函數。 我想在傳播到基本屬性的子級中設置默認值。 我想做這樣的事情:

public partial class baseclass
{
    public baseclass() {
        //never called if instantiated from baseclass(string newp1)
        p1 = "";
        p2 = "google";
    }

    public baseclass(string newp1) {
        p1 = newp1; //p2 will be "" and p1 will be newP1
    }

    public string p1 { get; set; }
    public string p2 { get; set; }
}

public partial class childclass : baseclass
{
    public childclass() { 
        //How can I call this to set some default values for the child?
        p2 = "facebook";
    }

    public childclass(string newp1) : base(newp1) {
        p1 = newp1; //p2 needs to be "facebook"
    }

}

如果在多個構造函數中有重復的代碼,請使用構造函數鏈接:

public class baseclass
{
    public baseclass() : this("google") { }
    public baseclass(string newp1)
    {
       p1 = newp1; // the only place in your code where you init properties
       p2 = "";
    }

    public string p1 { get; set; }
    public string p2 { get; set; }
}

子類應繼承baseClass

public class childclass : baseclass
{
    public childclass() : this("facebook") { } // you can also call base here
    public childclass(string newp1) : base(newp1) { }
}

還要記住, parital只允許您將類/方法定義分成多個部分(例如,將其保留在不同的文件中)。 當您正在生成類(例如從數據庫表)但仍要在生成的類中添加/自定義某些內容時,此功能很有用。 如果將定制的代碼直接放入生成的文件中,則在重新生成類之后,它將丟失。 閱讀更多

您可以在基類中創建一個受保護的構造函數,並在子類中調用它:

    public class Base
    {
       public Base(int value1, int value2) { ... }
       protected Base(string value1) { ... } // only for child class
    }

    public class Child : Base
    {
       public Child() : Base("Value") { ... }
    }

暫無
暫無

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

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