如何将基本参数从重载构造函数传递到派生类

时间:2015-05-19 15:21:04

标签: c# class inheritance

主要

static void Main(string[] args)
    {
        string name = "Me";
        int height = 130;
        double weight = 65.5;
        BMI patient1 = new BMI();
        BMI patient2 = new BMI(name,height,weight);

        Console.WriteLine(patient2.Get_height.ToString() + Environment.NewLine + patient1.Get_height.ToString() );
        Console.ReadLine();
    }

基类

class BMI
{ 
    //memberVariables
    private string newName;
    private int newHeight;
    private double newWeight;

    //default constructor
    public BMI(){}

    //overloaded constructor
    public BMI(string name, int height, double weight)
    {
        newName = name;
        newHeight = height;
        newWeight = weight;
    }

    //poperties
    public string Get_Name
    {
        get { return newName; }
        set { newName = value;}
    }

    public int Get_height 
    {
        get { return newHeight; }
        set { newHeight = value; } 
    }

    public double Get_weight 
    {
        get { return newWeight; }
        set { newWeight = value; }
    }
}

派生类

class Health : BMI
{
    private int newSize;
    public Health(int Size):base()
    {
        newSize = Size;
    }
}

如何将基本参数从BMI基类中的重载构造函数传递到Derived Class? 任何时候我尝试将它们传递给基本参数我得到无效的表达错误。 或者我只需要将它们传递到主要的Health对象中? 例如

class Health : BMI
{
    private int newSize;

     public Health(int Size, string Name, int Height, double Weight)
    {
        newSize = Size;
        base.Get_Name = Name
        base.Get_weight = Weight;
        base.Get_height = Height;
    }
}

3 个答案:

答案 0 :(得分:3)

构造函数不是继承的,所以是的,你需要为基类创建一个新的构造函数,但是你可以使用适当的参数调用基础构造函数:

 public Health(int size, string name, int height, double weight)
    : base(name, height, weight)
{
    newSize = size;
}

答案 1 :(得分:1)

像这样:

class Health : BMI
{
    private int newSize;

    public Health(int Size, string Name, int Height, double Weight)
        : base(Name, Height, Weight)
    {
        newSize = Size;
    }
}

答案 2 :(得分:0)

为什么不能调用基类构造函数来传递像

这样的参数
public Health(int Size, string Name, int Height, double Weight)  
    : base(Name, Height, Weight)
{
    newSize = Size;
}