本文實例講述了C#實現將數組內元素打亂順序的方法。分享給大家供大家參考。具體如下:
1.泛型類代碼
//泛型類class Item<T>{ T[] item; //構造函數 public Item(T[] obj) { item = new T[obj.Length]; for (int i = 0; i < obj.Length; i++) { item[i] = obj[i]; } } public Type ShowType() { return typeof(T); } //返回類型 public T[] GetItems() { return item; } //返回原數組 //返回打亂順序后的數組 public T[] GetDisruptedItems() { //生成一個新數組:用于在之上計算和返回 T[] temp; temp = new T[item.Length]; for (int i = 0; i < temp.Length; i++) { temp[i] = item[i]; } //打亂數組中元素順序 Random rand = new Random(DateTime.Now.Millisecond); for (int i = 0; i < temp.Length; i++) { int x, y; T t; x = rand.Next(0, temp.Length); do { y = rand.Next(0, temp.Length); } while (y == x); t = temp[x]; temp[x] = temp[y]; temp[y] = t; } return temp; }}
2.Main函數調用
static void Main(string[] args){ int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //輸出數組類型 Item<int> disrupter = new Item<int>(array); Console.WriteLine("數組類型:" + disrupter.ShowType().ToString()); //輸出數組 Console.Write("原輸入數組為:"); for (int i = 0; i < array.Length; i++) { Console.Write(array[i].ToString() + ' '); } Console.WriteLine(); //輸出一個打亂后數組 int[] disruptedArray = disrupter.GetDisruptedItems(); Console.Write("打亂后數組為:"); for (int i = 0; i < disruptedArray.Length; i++) { Console.Write(disruptedArray[i].ToString() + ' '); } Console.WriteLine(); Console.ReadLine();}
3.運行結果
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答