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

13 浏览
0 Comments

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

这个问题已经有了答案

C#中调用基类构造函数

Main函数

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基类的重载构造函数中将基本参数传递到派生类中?

每次我试图将它们传递到基本参数中,我都会得到无效的表达式错误。

还是我只需将它们传递到主函数中的一个“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;
    }
}

admin 更改状态以发布 2023年5月25日
0
0 Comments

像这样:

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

0
0 Comments

构造函数不会被继承,所以你需要为基类创建一个新的构造函数,但你可以使用正确的参数调用基类构造函数:\n

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

0