C#重载构造函数不能仅在参数修饰符的使用上有所不同

C# Overloaded constructor cannot differ on use of parameter modifiers only

当我尝试执行此操作时,我在标题中收到错误 ID 为 CS0851 的编译器错误:

public class Cells {

    public Cells(params Cell[] cells) : this(cells) {}

    public Cells(Cell[] cells) { ... }
}

我知道我可以通过摆脱第一个构造函数并要求代码使用后面的构造函数(强制转换为调用构造函数的数组)来解决这个问题,但我认为这不是一个好的结果。我理解为什么编译器可能无法区分具有这些相似签名的构造函数。

问题是:有没有什么方法可以让它真正发挥作用?

   Cells c1 = new Cells(new Cell[] { new Cell(1), new Cell(2)});
   Cells c2 = new Cells(new Cell(4), new Cell(5));

这是使用单声道,可能是新手问题。

第二种情况的静态构造函数怎么样?

public class Cells
{
    public Cells(Cell[] cells)
    {

    }

    public static Cells getCells(params Cell[] cells)
    {
        return new Cells(cells);
    }
}

这是我看到的最简单的方法。

您可以使用 params 构造函数传递单个项目和数组,不需要两个构造函数。

using System;

public class Cell
{
    public Cell(int x) {}
}

public class Cells
{
    public Cells(params Cell[] cells) { Console.WriteLine("Called with " + cells.Length.ToString() + " elements"); }
}

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.Write("Test #1: ");
           Cells c1 = new Cells(new Cell[] { new Cell(1), new Cell(2)});
            Console.Write("Test #2: ");
           Cells c2 = new Cells(new Cell(4), new Cell(5));
        }
    }
}

Run Code