【问题标题】:Chaining Constructors [closed]链接构造函数[关闭]
【发布时间】:2015-02-26 21:55:14
【问题描述】:

我试图更好地理解 C# 中构造函数的链接,但遇到了以下问题。

class Item
{
    private string _name;
    private string _category;
    private int _sku;
    private double _price;

    // default values
    public Item()
    {
        _name = "";
        _category = "Sale Item";
        _sku = 123;
        _price = 1.99;
    }

    public Item(string name, double price) : this()
    {
        this._name = name;
        this._price = price;
    }

    public Item(string name, string category, int sku, double price)
    {
        this._name = name;
        this._category = category;
        this._sku = sku;
        this._price = price;
    }

    public string Name
    {
        get { return this._name; }
    }

    public string Category
    {
        get { return this._category; }
    }

    public int SKU
    {
        get { return this._sku; }

    public double Price
    {
        get { return this._price; }
    }
}

我的想法是使用无参数构造函数来设置默认值,并使用参数化构造函数只更改那些需要更新的值。

不幸的是,这不起作用。代码无法编译。错误消息是 1729:没有采用 2 个参数的构造函数。我意识到这不是通常链接构造函数的方式,但我不明白为什么编译失败,因为在调用第二个构造函数 Item(string name, double price) 之前首先调用了无参数构造函数 Item()。

任何见解和建议将不胜感激。

【问题讨论】:

  • 由于 SKU 和 Price 属性,您的代码会出现编译器错误。除此之外,它编译得很好。显示你的实际代码。
  • 请同时包含实际发生编译错误的代码。
  • 代码编译和运行对我来说很好,除了你在类定义中缺少一个括号并且两个属性不是正确的类型。请提供一个示例来说明所描述的问题。
  • @Selman22:当编译器抱怨构造函数中的参数数量时,我不确定属性 SKU 和 Price 会有什么问题,
  • @PBrenek 那些属性的类型是string 现在你已经修复了.....

标签: c# constructor chaining


【解决方案1】:

链式构造函数本身没有问题,您得到的错误与使用 2 个 specific 参数实例化它的其他代码有关,它们没有提供 specific 构造函数。

您需要添加另一个与该签名匹配的 2 参数构造函数来修复该错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多