我有一个名为message的类,我正在尝试为此类生成多个对象并将这些值存储在列表中,但我的列表最后具有相同的元素。 这是我的代码。
public class Message
{
public int id { get; set; }
public string Data { get; set; }
public List<String> _messageCategories { get; set; }
public List<double> _relevanceScore { get; set; }
public Message(List<String> messageCategories, List<double> relevanceScore)
{
_messageCategories = messageCategories;
_relevanceScore = relevanceScore;
}
}
public List<Message> message=new List<Message>();
public void Randommesg()
{
k1 = 10;
for (int i = 0; i <= k1; i++)
{
List<double> rscore = new List<double>();
List<string> messagetype = new List<string>();
Message msg = new Message(messagetype, rscore);
messagetype.Clear();
rscore.Clear();
Random r = new Random();
int mnum = r.Next(6);
while (messagetype.Count <= mnum)
{
Random r1 = new Random();
string[] arr = { "sports", "reebok", "nike", "adidas", "cookware", "home decor", "tools", "toys", "clothes", "appliances", "electronics", "phones", "computers" };
int i1 = r.Next(13);
String mesgtype = arr[i1];
if (messagetype.Contains(mesgtype))
{
continue;
}
else
{
messagetype.Add(mesgtype);
}
}
while (rscore.Count <= messagetype.Count)
{
Random r1 = new Random();
Double i2 = r1.NextDouble();
String score1 = i2.ToString("0.#");
Double score2 = double.Parse(score1);
rscore.Add(score2);
}
msg._messageCategories = messagetype;
msg._relevanceScore = rscore;
msg.id = i;
message.Add(msg);
}
}
我期待消息列表中有10条不同的消息,但我最终在消息列表中有相同的消息。任何人都可以帮我找到问题所在。 提前谢谢
答案 0 :(得分:1)
在调用Random
或Next
方法之前,您不应每次都创建NextDouble
的新实例。将您的Randommesg
更改为以下内容:
public void Randommesg()
{
Random r = new Random();
int k1 = 10;
for (int i = 0; i <= k1; i++)
{
List<double> rscore = new List<double>();
List<string> messagetype = new List<string>();
Message msg = new Message(messagetype, rscore);
messagetype.Clear();
rscore.Clear();
int mnum = r.Next(6);
while (messagetype.Count <= mnum)
{
string[] arr = { "sports", "reebok", "nike", "adidas", "cookware", "home decor", "tools", "toys", "clothes", "appliances", "electronics", "phones", "computers" };
int i1 = r.Next(13);
String mesgtype = arr[i1];
if (messagetype.Contains(mesgtype))
{
continue;
}
else
{
messagetype.Add(mesgtype);
}
}
while (rscore.Count <= messagetype.Count)
{
Double i2 = r.NextDouble();
String score1 = i2.ToString("0.#");
Double score2 = double.Parse(score1);
rscore.Add(score2);
}
msg._messageCategories = messagetype;
msg._relevanceScore = rscore;
msg.id = i;
message.Add(msg);
}
}