C# - 上一个参数的默认参数值

时间:2014-08-23 10:10:32

标签: c# constructor overloading default-parameters

namespace HelloConsole
{
    public class BOX
    {
        double height, length, breadth;

        public BOX()
        {

        }
        // here, I wish to pass 'h' to remaining parameters if not passed
        // FOLLOWING Gives compilation error.
        public BOX (double h, double l = h, double b = h)
        {
            Console.WriteLine ("Constructor with default parameters");
            height = h;
            length = l;
            breadth = b;
        }
    }
}

// 
// BOX a = new BOX(); // default constructor. all okay here.
// BOX b = new BOX(10,20,30); // all parameter passed. all okay here.

// BOX c = new BOX(10);
// Here, I want = length=10, breadth=10,height=10;

// BOX d = new BOX(10,20);
// Here, I want = length=10, breadth=20,height=10;

问题是:'要实现上述目标,'构造函数重载'(如下所示)是唯一的选择吗?

public BOX(double h)
{
    height = length = breadth = h;
}

public BOX(double h, double l)
{
    height = breadth = h;
    length = l;
}

2 个答案:

答案 0 :(得分:4)

您可以创建多个相互调用的构造函数:

public BOX(double h) : this(h, h, h) { }
public BOX(double h, double l) : this(h, l, h) { }
public BOX(double h, double l, double b)
{
    height = h;
    length = l;
    breadth = b;
}

另一种解决方案是使用默认值null

public BOX(double h, double? l = null, double? b = null)
{
    height = h;
    breadth = b ?? h;
    length = l ?? h;
}

这最后一种方法也让你只用高度和广度来调用它:

var box = new BOX(10, b: 15); // same as new BOX(10, 10, 15);

答案 1 :(得分:1)

构造函数重载是最好/最干净的解决方案。如果您只想拥有一个构造函数,则可以使用params array。这仅适用于参数类型相同的情况。

public clas BOX 
{
    public BOX (params double[] d)
    {     
        switch(d.Length) 
        {
            case 3:
                height = d[0];
                length = d[1];
                breadth = d[2];
                break;
            case 2:
                height = d[0];
                breadth = d[1];
                length = d[0];
                break;
            case 1:
                height = d[0];
                breadth = d[0];
                length = d[0];
                break;
             case 0:
                // no parameters
                break;
             default:
                // we rather not throw 
                // http://msdn.microsoft.com/en-us/library/ms229060(v=vs.110).aspx
                // throw new ArgumentException();
                Debug.Assert(d.Length<4, "too many arguments");
                break;
          }   
    }
}