我想製作一個簡單的程序(抽獎號碼生成器),該程序在特定範圍內接受數字並將其洗牌「n」次,在每次洗牌後它會選擇一個隨機數並將其從給定範圍的列表移動到新列表中,並且將其執行「n」次(直到它選擇特定數量的數字,準確地說是7)。我找到了一個完全符合該算法的算法(擴展方法或混排通用列表)。但是我並不是那麼喜歡編程,而且我在將結果(帶有繪製數字的列表)顯示給TextBox或Label時遇到了問題,但是我已經將它與MessageBox配合使用。但有了TextBox/Label,我得到錯誤「名稱*在當前上下文中不存在」。我已經搜索了一個解決方案,但沒有任何幫助。C#在當前上下文中不存在名稱brojevi
下面的代碼:
private void button1_Click(object sender, EventArgs e)
{
List<int> numbers;
numbers = Enumerable.Range(1, 39).ToList();
numbers.Shuffle();
}
private void brojevi_TextChanged(object sender, EventArgs e)
{
}
}
}
/// <summary>
/// Class for shuffling lists
/// </summary>
/// <typeparam name="T">The type of list to shuffle</typeparam>
public static class ListShufflerExtensionMethods
{
//for getting random values
private static Random _rnd = new Random();
/// <summary>
/// Shuffles the contents of a list
/// </summary>
/// <typeparam name="T">The type of the list to sort</typeparam>
/// <param name="listToShuffle">The list to shuffle</param>
/// <param name="numberOfTimesToShuffle">How many times to shuffle the list, by default this is 5 times</param>
public static void Shuffle<T>(this List<T> listToShuffle, int numberOfTimesToShuffle = 7)
{
//make a new list of the wanted type
List<T> newList = new List<T>();
//for each time we want to shuffle
for (int i = 0; i < numberOfTimesToShuffle; i++)
{
//while there are still items in our list
while (listToShuffle.Count >= 33)
{
//get a random number within the list
int index = _rnd.Next(listToShuffle.Count);
//add the item at that position to the new list
newList.Add(listToShuffle[index]);
//and remove it from the old list
listToShuffle.RemoveAt(index);
}
//then copy all the items back in the old list again
listToShuffle.AddRange(newList);
//display contents of a list
string line = string.Join(",", newList.ToArray());
brojevi.Text = line;
//and clear the new list
//to make ready for next shuffling
newList.Clear();
break;
}
}
}
}
這可能是一個作用域的問題:http://msdn.microsoft.com/en-us/library/aa691132 %28VS.71%29.aspx。然而,很難說,因爲你沒有說錯誤在哪裏。 – Bobson 2013-02-27 20:47:14
顯示MessageBox的代碼在哪裏? – XORcist 2013-02-27 20:47:27
從字面上看,「名稱*不存在」還是「*」表示特定的符號? – 2013-02-27 20:48:21