經過很長時間後,我設法從我的程序中獲得了我在第一個問題中詢問的問題。它將一個隨機數添加到列表中以用作ID號,然後將其導出到Excel。然而,當我在數據文件中使用超過2個數據成員時,我遇到了一個問題:我產生的隨機數字翻倍,導致我的程序崩潰。C#中的隨機數發生器問題#
static Dictionary<string,Backup> getData()
{
Dictionary<string, Backup> bDict = new Dictionary<string, Backup>();
StreamReader reader = new StreamReader("/data/storedata.txt");
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] parts = line.Split(' ');
string item = parts[0];
string owner = parts[1];
Random rnd = new Random();
int test = rnd.Next(item.Length+10000);//For every 'item' a Random number is generated.(the +10000 is simply to produce a 4-digit number)
//Console.WriteLine(test);//Testing
Backup BP = new Backup(item, owner,test);
bDict.Add(test.ToString(), BP);//Adding to the Dictionary.
//Console.WriteLine(string.Format("{0}, {1}, {2}", item, test, owner));
}
return bDict;
}//Read file, Grabed data and stored it in a List.
後我是什麼/試圖做的是有幾分檢查的,如果兩個數字是相同的一個新號碼作爲替代(或做同樣的事情的其他方式)產生的。我試過如果陳述,但VS不斷問我是否打算與其他東西比較。我在Stackoverflow上看過這裏的東西,但答案並不適合我的代碼。 任何幫助表示讚賞。
FAQ 數據文件將具有向上的500 '的項目' 沒有最小/最大
歡呼聲
我很難相信你找不到的SO另一個例子中,這個問題是如此頻繁它的幾乎符合常見問題。在「提問」區域輸入問題標題可以獲得很多可能的答案。 –
[Revisiting randomness](http://msmvps.com/blogs/jon_skeet/archive/2009/11/04/revisiting-randomness.aspx) – Damith
我猜在這個實例中恐慌設置英寸循環內的語句幾乎沒有很快運行給予所有的io操作(特別是如果未註釋的話)。這會導致隨機數發生一些變化。如果環路比較緊密,那麼對OP來說就會更清楚。 – Bathsheba