简体   繁体   中英

C# force constructor's parameters to receive specific values

how can I force constructor's parameters to have specific values? In the example below I would like to have only 2-4 players.

I would like to have a compile error when I enter a wrong _numOfPlayers value. Another way to warn the coder from using the constructor in a wrong way will be welcome.

    public class Rules
{
    public Rules(int _numOfPlayers)
    {

        numOfPlayers = _numOfPlayers;
    }
 public readonly int numOfPlayers;

}

A more complicated situation:

    public class Rules
{
    public Rules(int _numOfPlayers, int _money)
    {

        numOfPlayers = _numOfPlayers;
        money = _money;
    }
 public readonly int numOfPlayers;
 public readonly int money;

}

Here I would like to have only specific combinations: 2 players, 2000 money. 2 players, 1000 money. 3 players, 700 money. 4 players, 500 money.

How can I promise that?

There's no practical way to constrain types like this at compile-time in C#. I think the best you'll be able to do in your example is maybe create an enum that only has the valid values. Then your code won't compile if you using anything besides those values.

enum PlayerCount {Two = 2, Three, Four};

Then your constructor would look like this:

public Rules(PlayerCount count)
{
   numOfPlayers = (int)count;
}

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