我正在尝试使用以下方法生成随机产品列表,但我多次获得相同的产品实例。
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
我读到 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;
}