【问题标题】:"Does not contain a constructor that takes 0 arguments", and how to access protected values from another class“不包含带 0 个参数的构造函数”,以及如何从另一个类访问受保护的值
【发布时间】:2015-05-01 03:06:07
【问题描述】:

我有两个问题。一个是Box 正在从Rectangle 继承值,但我收到错误“不包含采用 0 个参数的构造函数”。什么意思?

class Box : Rectangle
{
    private double height;
    private double Height
    {
        get { return height; }
        set { if (value > 0) height = value; }
    }

    //Error for box: Does not contain a constructor that takes 0 arguments
    public Box (double l, double w, double h)
    {
        length = l;
        width = w;
        height = h;
    }

    public double findArea(double h)
    {
        return h * h;
    }

    public double findVolume(double l, double w, double h)
    {
        return l * w * h;
    }

    public String toString()
    {
        return ("The volume is " + " cm");
    }
}

另一个问题我无法从 Rectangle 类访问 protected 值,我也不确定如何处理,因为我阅读并尝试了其他网站的方法,但我不太明白。

【问题讨论】:

  • 意思是:“Compiler Error CS1729”。真的不难找。您是否尝试在包含错误的错误列表行上按 F1?

标签: c# arguments protected


【解决方案1】:

不包含带 0 个参数的构造函数

这是因为您的基类Rectangle 实际上不包含这样的构造函数,但是您没有指定要调用的其他构造函数。当您的类的构造函数没有指定要调用的基类构造函数时,无参数构造函数是默认值,但由于基类中不存在基类构造函数,因此您会收到编译时错误。

根据您发布的代码推断 Rectangle 的声明是什么,我猜您希望您的 Box 构造函数如下所示:

public Box (double l, double w, double h)
    : base(l, w)
{
    height = h;
}

至于无法访问protected 成员,那根本不可能。派生类始终可以访问任何具有protected 可访问性的基类成员。如果您在执行此操作时遇到问题,则说明您做错了其他事情。

但如果没有关于问题的具体细节,就无法说出那是什么。您需要提供您收到的确切错误消息,以及可靠地重现问题的a good, minimal, complete code example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多