将随机数写入对象数组

时间:2017-07-06 14:41:12

标签: c# arrays random

我目前正在开发模拟器,它应该模仿某种业务逻辑。 我尝试通过从两个字符串数组中挑选两个随机字符串来创建类Suggestion的对象。该方法应返回Suggestion个对象的数组。数组长度也是可变的。现在,返回的数组应该在控制台中打印出来。

这是我的班级Suggestion

 public class Suggestion
    {
        public Suggestion(string aktenName, string relevanz)
        {
            MAktenName = aktenName;
            MRelevanz = relevanz;
        }

        public string MAktenName { get; private set; }

        public string MRelevanz { get; private set; }
    }

我的其他课程包括“逻辑”和主要方法如下:

 private static void Main()
        {
            var test = GetSuggestions();

            for (var i = 0; i < test.Length; i++)
            {
                Console.WriteLine(test[i].MAktenName + "-" + test[i].MRelevanz + "%");
            }

            Console.ReadLine();
        }

        public static Suggestion[] GetSuggestions()
        {
            var random = new Random();
            var suggestionsCount = random.Next(1, 10);
            var suggestions = new Suggestion[suggestionsCount];

            string[] names =
            {
                "721/12", "345/93", "478/54", "876/39", "546/27", "481/56", "824/39", "897/51",
                "574/48"
            };
            string[] relevance =
            {
                "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"
            };

            for (var i = 0; i < suggestionsCount; i++)
            {

                var sugName = names[new Random().Next(0, names.Length)];
                var sugRelevance = relevance[new Random().Next(0, relevance.Length)];

                suggestions[i] = new Suggestion(sugName, sugRelevance);
            }
            return suggestions;
        }

我的问题是它打印出字符串数组sugNamesugRelevance的随机组合,并打印出可变数量的这些,但类Suggestions的所有对象都是相同。 就像我的结果是:

  

345 / 93-20%

     

345 / 93-20%

     

345 / 93-20%

     

345 / 93-20%

我认为它与new Random().Next(0, names.Length)有关,但我不确定。

1 个答案:

答案 0 :(得分:0)

而不是

var sugName = names[new Random().Next(0, names.Length)];
var sugRelevance = relevance[new Random().Next(0, relevance.Length)];

写:

var sugName = names[random.Next(0, names.Length)];
var sugRelevance = relevance[random.Next(0, relevance.Length)];