2015-05-19 65 views
0

主要如何从重载的构造传递基础参数到派生类

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

我会建议将您的属性重命名为“高度”,“名称”和“重量”。让它们以'Get'作为前缀使得它看起来像是在调用一个方法或访问一个只读属性。 –

回答

3

构造函数是不可继承的,所以是的,你需要创建基类一个新的构造,但你可以叫用正确的参数基本构造:

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

您的基础构造函数的外形不正确。 – d347hm4n

+1

@ d347hm4n谢谢,修正。 –

1

筛选:

class Health : BMI 
{ 
    private int newSize; 

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

你为什么不能调用基类的构造函数传递参数一样

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