C#如何以相同规则同步打乱PictureBox数组和int类型数组
解决方案
直接修复现有代码
报错核心原因是你声明的temp变量是PictureBox类型,无法存储int类型的数值,交换不同类型数组时要分别声明对应类型的临时变量,修改后可正常运行的代码如下:
PictureBox[] cards = new PictureBox[13]; int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 }; Random rnd = new Random(); for (int i = 0; i < cards.Length - 1; i++) { int j = rnd.Next(i, cards.Length); // 交换PictureBox数组元素 PictureBox tempCard = cards[j]; cards[j] = cards[i]; cards[i] = tempCard; // 用int类型临时变量交换int数组元素 int tempNum = numbers[j]; numbers[j] = numbers[i]; numbers[i] = tempNum; }
通用封装方案
如果后续需要频繁用到不同类型数组的同步打乱,可以封装为泛型方法,适配任意两种类型的等长数组,复用性更强:
// 泛型同步打乱方法,支持任意两种类型的等长数组 public static void ShuffleTwoArrays<T1, T2>(T1[] array1, T2[] array2) { // 校验两个数组长度一致 if (array1.Length != array2.Length) throw new ArgumentException("两个数组长度必须相同"); Random rnd = new Random(); for (int i = 0; i < array1.Length - 1; i++) { int j = rnd.Next(i, array1.Length); // 交换第一个数组元素 (array1[i], array1[j]) = (array1[j], array1[i]); // 交换第二个数组元素 (array2[i], array2[j]) = (array2[j], array2[i]); } }
注:上面代码里的元组交换语法
(a,b)=(b,a)是C# 7.0及以上版本支持的特性,如果你的开发环境版本较低,替换为对应类型的临时变量交换逻辑即可。
调用方法:
PictureBox[] cards = new PictureBox[13]; int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 }; ShuffleTwoArrays(cards, numbers);
内容的提问来源于stack exchange,提问作者Erik Vishnyak
相关产品推荐
相关产品推荐

