随机产品列表被覆盖

Kri*_*hna 0 c#

我正在尝试使用以下方法生成随机产品列表,但我多次获得相同的Product实例.

Output for count 5:
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Run Code Online (Sandbox Code Playgroud)

我读List类型是一个引用类型&它覆盖东西.以下是我的代码.我错过了可以给我独特的产品实例的东西吗?谢谢,谢谢你的帮助.

public List<Product> ProductGroupGenerator(int count)
    {
        List<Product> pList = new List<Product>();

        for (int i = 0; i < count; i++)
        {
            Random r = new Random();
            string alphabet = "abcdefghijklmnopqrstuvwyxzeeeiouea";
            Func<char> randomLetter = () => alphabet[r.Next(alphabet.Length)];
            Func<int, string> makeName =
              (length) => new string(Enumerable.Range(0, length)
                 .Select(x => x == 0 ? char.ToUpper(randomLetter()) : randomLetter())
                 .ToArray());

            //string last = makeName(r.Next(7) + 7);
            //string company = makeName(r.Next(7) + 7) + " Inc.";

            string prodName = makeName(r.Next(5) + 5);
            int unitsInStock = r.Next(100);
            float unitPrice = (float)(r.NextDouble() * 10);

            Product p = new Product();
            p.Name = prodName;
            p.UnitsInStock = unitsInStock;
            p.UnitPrice = unitPrice;

            pList.Add(p);

            p = null;
        }

        return pList;
    }
Run Code Online (Sandbox Code Playgroud)

Aus*_*nen 7

当调用太快时,多个Random r = new Random()将生成具有相同种子的Randoms.

在for循环之外声明它一次,你应该有更好的值.

    Random r = new Random();
    for (int i = 0; i < count; i++)
    {
Run Code Online (Sandbox Code Playgroud)