这是我的第 1 周 OOP,所以我退出新手,如果问题是关于基础的,我很抱歉,因为我无法理解它。我不明白构造函数重载和链接之间的区别。我正在使用以下父类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicle_Application
{
abstract class Vehicle
{
private string color;
public string Color { get { return color; } set { color = value; }}
private double fuelTankSize;
public double FuelTankSize { get {return fuelTankSize;} set { fuelTankSize = value;}}
private double efficiency;
public double Efficiency { get { return efficiency; } set { efficiency = value; } }
private double fullTankMileage = 100;
public double milesPerGalon;
public void calculateMPG()
{this.milesPerGalon = (fullTankMileage/(fuelTankSize/4))* efficiency;}
}
}
从中驱动以下子类“汽车”:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicle_Application
{
class Car : Vehicle
{
public Car(string color = null)
{ this.Color = color; }
public int NumberOfTyres;
public Car(string color, int noOfTyres, double fuelTankSize, double efficiency)
{
this.Color = color;
this.NumberOfTyres = noOfTyres;
this.FuelTankSize = fuelTankSize;
this.Efficiency = efficiency;
this.calculateMPG();
}
}
}
该程序如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicle_Application
{
class Program
{
static void Main(string[] args)
{
Car car1 = new Car("Red", 4, 5, 6);
Car car2 = new Car("Red");
car1.Color = "Red";
car2.Color = "Green";
System.Console.WriteLine("The color of the first vehicle is: ");
Console.WriteLine(car1.Color);
System.Console.WriteLine("The color of the second vehicle is: ");
Console.WriteLine(car2.Color);
Console.WriteLine(car1.milesPerGalon);
Console.ReadLine();
}
}
}
现在我的困惑来自 constructor Car
。实例
public Car(string color = null)
和 public Car(string color, int noOfTyres, double fuelTankSize, double efficiency)
两者都有不同的签名(nr. of parameters)并且都Program
通过调用重载
Console.WriteLine(car2.Color);
和 Console.WriteLine(car1.milesPerGalon);
. 程序识别出car1
有四个参数,因此使用汽车的第二个实例。而car2
只有一个参数,因此Program
使用汽车的第一个实例。
相同的汽车实例在我看来就像是链接的完美示例,因为我在 Internet 上找到了解释与链接相同过程的示例。
这里不涉及构造函数链,它们只是构造函数的两个不同重载。
构造函数链看起来像这样:
public Car(string color = null) : this(color, 4, 5, 6)
{
}
public Car(string color, int noOfTyres, double fuelTankSize, double efficiency)
{
this.Color = color;
this.NumberOfTyres = noOfTyres;
this.FuelTankSize = fuelTankSize;
this.Efficiency = efficiency;
this.calculateMPG();
}
注意: this()
第一个构造函数的调用。您可以通过传递颜色和一些默认值来链接到另一个 ctor。
如果它有一个,你也可以链接到基类 ctor(来自 Vehicle):
public class Vehicle
{
public Vehicle(Color color)
{
// whatever
}
}
public class Car : Vehicle
{
public Car(Color color) : base(color)
{
// whatever
}
}
InBetween 在评论中的更正:
必须始终调用 Vehicle 的构造函数,如果不先构造 Vehicle 就不能创建 Car。如果没有显式调用其他基本构造函数,则会隐式调用默认构造函数(如果有的话)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句