我有一个正在处理我创建的对象的类;
StockItem2 = new CarEngine("Mazda B6T", 1252, 8025, 800, "Z4537298D");
//StockItem2 = new CarEngine("description", cost, invoice #, weight, engine #)
我还有一个静态int,将最后一个发票号设置为10,000。
internal static int LastStockNumber = 10000;
如果没有输入发票号码,我希望它每次自动分配一个并递增1,所以10,001 / 10,002等。
CarEngine有2个构造函数,如果没有输入,则这个构造函数用于分配发票编号。 它需要描述,成本,重量,引擎数量,并且应该从10,001开始自动分配,但它似乎一次增加2-3,任何想法为什么?
public CarEngine(string Description, int CostPrice, int Weight, string EngineNumber)
: base(Description, CostPrice, Weight)
{
LastStockNumber++;
StockNumber = LastStockNumber;
this.CostPrice = CostPrice;
this.Description = Description;
this.Weight = Weight;
this.EngineNumber = EngineNumber;
}
// this is in the stockitem class //
public StockItem(string Description, int CostPrice)
{
LastStockNumber++;
StockNumber = LastStockNumber;
this.Description = Description;
this.CostPrice = CostPrice;
}
//this is in the heavystockitem class//
public HeavyStockItem(string Description, int CostPrice, int Weight) : base(Description, CostPrice)
{
StockNumber = LastStockNumber;
LastStockNumber++;
this.CostPrice = CostPrice;
this.Description = Description;
this.Weight = Weight;
}
答案 0 :(得分:2)
您可能在基类和派生类构造函数中递增LastStockNumber。
答案 1 :(得分:1)
我从签名中猜测,CarEngine
继承自HeavyStockItem
继承自StockItem
。
鉴于此,在创建新的CarEngine
对象时,它将调用基础构造函数,该构造函数将调用其自己的基础构造函数。
由于每个构造函数都具有以下代码:LastStockNumber++;
然后对于CarEngine
,数字将增加3倍,对于HeavyStockItem
,它将增加两倍,并且对于StockItem
1}}它只会增加一次。
鉴于您正在调用基础构造函数,您应该只初始化类的唯一内容。尝试将代码更改为以下内容:
public CarEngine(string description, int costPrice, int weight, string engineNumber)
: base(description, costPrice, weight)
{
EngineNumber = engineNumber;
}
//this is in the heavystockitem class//
public HeavyStockItem(string description, int costPrice, int weight)
: base(description, costPrice)
{
Weight = weight;
}
// this is in the stockitem class //
public StockItem(string description, int costPrice)
{
LastStockNumber++;
StockNumber = LastStockNumber;
Description = description;
CostPrice = costPrice;
}
对于奖励积分,请注意我已根据普遍接受的C#标准将构造函数参数从PascalCase更改为camelCase。这有助于您区分属性(首字母大写)和参数(首字母小写)。