[英]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.