代码之家  ›  专栏  ›  技术社区  ›  Ofirster

C#强制构造函数的参数接收特定值

  •  3
  • Ofirster  · 技术社区  · 7 年前

    如何强制构造函数的参数具有特定值?

    我希望在输入错误的值时出现编译错误。 另一种警告编码器不要以错误的方式使用构造函数的方法将受到欢迎。

        public class Rules
    {
        public Rules(int _numOfPlayers)
        {
    
            numOfPlayers = _numOfPlayers;
        }
     public readonly int numOfPlayers;
    
    }
    

        public class Rules
    {
        public Rules(int _numOfPlayers, int _money)
        {
    
            numOfPlayers = _numOfPlayers;
            money = _money;
        }
     public readonly int numOfPlayers;
     public readonly int money;
    
    }
    

    在这里,我只希望有具体的组合: 2名球员,2000美元。 3名球员,700美元。 4名球员,500美元。

    我怎么能保证?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Taylor Wood    7 年前

    在C#中,在编译时没有实际的方法来约束这样的类型。我认为在你的例子中,你能做的最好的事情就是创建一个 enum

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

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