当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现将数组内元素打乱顺序的方法

C#实现将数组内元素打乱顺序的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网