简体   繁体   English

在派生类的基类中设置默认属性

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

Ok so, I've run into an interested and probably simple problem. 好的,我遇到了一个有趣且可能很简单的问题。 I have a base class that is inherited by another class (child). 我有一个由另一个类(子级)继承的基类。 I have the same parameterless constructor in the base and the child. 我在基础和孩子中有相同的无参数构造函数。 I would like to set defaults in the child that propagate into the base properties. 我想在传播到基本属性的子级中设置默认值。 I would like to do something like this: 我想做这样的事情:

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"
    }

}

Use constructors chaining if you have duplicated code in several constructors: 如果在多个构造函数中有重复的代码,请使用构造函数链接:

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; }
}

Child class should inherit baseClass 子类应继承baseClass

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

Also keep in mind that parital just allows you split class/method definiton in several parts (eg keep it in different files). 还要记住, parital只允许您将类/方法定义分成多个部分(例如,将其保留在不同的文件中)。 It is useful when you are generating classes (eg from database tables) but still want to add/customize something in generated classes. 当您正在生成类(例如从数据库表)但仍要在生成的类中添加/自定义某些内容时,此功能很有用。 If you will put customized code directly into generated files, then it will be lost after classes re-generation. 如果将定制的代码直接放入生成的文件中,则在重新生成类之后,它将丢失。 Read more 阅读更多

You can create a protected constructor in base class and call it in child class: 您可以在基类中创建一个受保护的构造函数,并在子类中调用它:

    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