简体   繁体   中英

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

I get the compiler error in the title with an error ID of CS0851 when I try and do this:

public class Cells {

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

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

I know I can get around this by getting rid of the first constructor and requiring code to use the later constructor (forcing the conversion to an array where the constructor is being called) but I think that's not a nice outcome. I understand why the compiler might have problems differentiating between the constructors with these similar signatures.

The question is: Is there some way I can actually get this to work?

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

This is using mono and is possibly a newbie question.

You can pass both single items and arrays using the params constructor, you don't need two constructors.

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

How about a static constructor for your second case?

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

    }

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

Its the simplest way I see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM