c# -前一个参数的默认参数值

本文关键字:参数 一个 默认 | 更新日期: 2023-09-27 18:19:14

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

c# -前一个参数的默认参数值

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

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);

构造函数重载是最好/最干净的解决方案。如果您只想要一个构造函数,您可以使用params数组。这只在参数类型相同的情况下有效。

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