在C#中的子类构造函数中初始化基类的字段

时间:2015-01-31 00:06:05

标签: c# constructor subclass base-class

我有一个带有三个字段的基类,但不是像这样正常的方式初始化它的字段:

class ParentClass
{
    public string Name { get; set; }
    public string Family { get; set; }
    public string Address { get; set; }

    public ParentClass(string Name, string Family, string Address)
    {
        this.Name = Name;
        this.Family = Family;
        this.Address = Address;

    }

}

class ChildClass : ParentClass
{
    public int StudentID { get; set; }
    public int StudentScore { get; set; }

    public ChildClass(string Name, string Family, string Address, int StudentID, int StudentScore)
        : base(Name, Family, Address)
    {

        this.StudentID = StudentID;
        this.StudentScore = StudentScore;

    }

    static void Main(string[] args)
    {
        var Pro = new ChildClass("John", "Greene", "45 Street", 76, 25);
        Console.WriteLine(Pro.Name + Pro.Family + Pro.Address + Pro.StudentID + Pro.StudentScore);
    }
}

我已初始化ChildClass构造函数中的字段,而没有显式调用基类构造函数,如下所示:

class ParentClass
{
    public string Name { get; set; }
    public string Family { get; set; }
    public string Address { get; set; }
}

class ChildClass : ParentClass
{
    public int StudentID { get; set; }
    public int StudentScore { get; set; }

    public ChildClass(int StudentID, int StudentScore)
    {
        Name = "John";
        Family = "Greene";
        Address = "45 Street";
        this.StudentID = StudentID;
        this.StudentScore = StudentScore;

    }
    static void Main(string[] args)
    {
        var Pro = new ChildClass(76, 25);
        Console.WriteLine(Pro.Name + Pro.Family + Pro.Address + Pro.StudentID + Pro.StudentScore);
    }
}

我知道我可以在父类本身初始化父类的字段,这是一个虚假的例子,但我想知道在现实生活和更复杂的情况下做这样的事情是否被认为是一种好习惯,我有什么理由不这样做吗?至于没有显式调用基类构造函数?

编辑:我更关心的是没有显式调用基类构造函数并在子类部分初始化它,所以我编辑了最后一部分,提到了要暴露的字段进行。

1 个答案:

答案 0 :(得分:2)

正如您已经看到的那样,这些字段已经"暴露了#34;。在第一个例子中,您仍然可以从派生类中获取这些变量。

至于不使用基类构造函数是好的做法,我会说不。通过只有一个参数化的基类构造函数,您可以确保该类的未来实现者初始化基类属性。例如,在你的第二个我可以写:

public ChildClass(int StudentID, int StudentScore)
{
    this.StudentID = StudentID;
    this.StudentScore = StudentScore;
}

没有错误。除此之外,您的样品之间的差异非常小。