【问题标题】:Is it possible to create a random list of integers inside a c# constructor?是否可以在 c# 构造函数中创建随机整数列表?
【发布时间】:2013-12-30 11:46:35
【问题描述】:

我创建了一个构造函数,最初创建一些硬编码值是可以的。现在是时候我需要随机创建值了。是否可以在构造函数中这样做。例如我有以下内容:

private Random _random;

public GuessingGame()
{
    this.Guesses = new List<Guess>();
    this.Target = new List<int>() { 1, 2, 3 };
    this._random = new Random();
}

public List<int> Target { get; set; }
public List<Guess> Guesses { get; set; }

我尝试创建一个new Random(),然后尝试分配它,但没有成功。在我的构造函数中创建随机整数的最佳方法是什么?

【问题讨论】:

  • 什么不起作用?有什么例外吗?
  • 只需在循环中调用 _random.Next 所需的次数并将值添加到列表中
  • 创建3个随机值列表的可能更紧凑的方法Target = Enumerable.Repeat(1, 3).Select(i =&gt; _random.Next()).ToList()

标签: c# .net random


【解决方案1】:
public GuessingGame()
{
    this.Guesses = new List<Guess>();
    this._random = new Random();
    this.Target = new List<int>();

    int randomCount = 3; // how many randoms
    int rndMin = 1; // min value of random
    int rndMax = 10; // max value of random


    for (int i = 0; i < randomCount; i++)
      this.Target.Add(this._random.Next(rndMin, rndMax));
} 

【讨论】:

    【解决方案2】:

    LINQ 版本:

    public GuessingGame() {
        _random = new Random();
        Target = Enumerable
                     .Repeat(0, how_many_items)
                     .Select(x => _random.Next(max_random_number_value))
                     .ToList();
        // ..the rest..
    }
    

    【讨论】:

      【解决方案3】:

      这行代码

      for(int i=0;i<10;i++)
      {
       this.Target.Add(this._random.Next(0,10));
      }
      

      用 0 到 9 之间的 10 个随机数填充目标列表

      private Random _random;
      
      public GuessingGame()
      {
          this.Guesses = new List<Guess>();
          this.Target = new List<int>() { 1, 2, 3 };
          this._random = new Random(DateTime.Now.Millisecond);  
          for(int i=0;i<10;i++)
          {
           this.Target.Add(this._random.Next(0,10));
          }
      
      
      }
      
      public List<int> Target { get; set; }
      public List<Guess> Guesses { get; set; }
      

      【讨论】:

        猜你喜欢
        • 2021-04-25
        • 1970-01-01
        • 2017-05-01
        • 2012-07-01
        • 2021-11-15
        • 2016-07-17
        • 2020-03-08
        • 2011-05-09
        相关资源
        最近更新 更多