[英]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));
这是使用单声道,可能是一个新手问题。
您可以使用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));
}
}
}
第二种情况下的静态构造函数怎么样?
public class Cells
{
public Cells(Cell[] cells)
{
}
public static Cells getCells(params Cell[] cells)
{
return new Cells(cells);
}
}
这是我看到的最简单的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.