0

I have a class that is dealing with objects i have created for example;

StockItem2 = new CarEngine("Mazda B6T", 1252, 8025, 800, "Z4537298D");
//StockItem2 = new CarEngine("description", cost, invoice #, weight, engine #)

I also have a static int setting the last invoice number to 10,000.

 internal static int LastStockNumber = 10000; 

If no invoice number is entered, i want it to auto assign one and increment by 1 each time, so 10,001 / 10,002 etc..

CarEngine has 2 constructors, this is the one that is meant to assign the invoice number if one is not entered. It takes the description, cost, weight, engine number and should autoassign from 10,001 onward but it seems to be incrementing by 2-3 at a time, any ideas why?

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;
    }
4

2 回答 2

2

您可能在基类和派生类构造函数中递增 LastStockNumber。

于 2013-10-02T05:23:27.170 回答
1

我从签名中猜测,因为您的CarEngine继承自HeavyStockItemwhich 继承自StockItem.

鉴于此,当创建一个新CarEngine对象时,它将调用基构造函数,而基构造函数将调用它自己的基构造函数。

由于每个构造函数都有以下代码:LastStockNumber++;那么对于 aCarEngine数字将增加 3 次,对于 aHeavyStockItem它将增加两次,对于 aStockItem它只会增加一次。

鉴于您正在调用基本构造函数,您应该只初始化您的类独有的东西。尝试将您的代码更改为以下内容:

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。这有助于您区分属性(首字母大写)和参数(首字母小写)。

于 2013-10-02T05:42:11.597 回答