小智 13
使用元组
int[] arr = { 1, 2, 3 };
(arr[0], arr[1]) = (arr[1], arr[0]);
Console.WriteLine(string.Format($"{arr[0]} {arr[1]} {arr[2]}")); // 2 1 3
Run Code Online (Sandbox Code Playgroud)
Sea*_*ayn 10
如果你真的只想交换,你可以使用这个方法:
public static bool swap(int x, int y, ref int[] array){
// check for out of range
if(array.Length <= y || array.Length <= x) return false;
// swap index x and y
var buffer = array[x];
array[x] = array[y];
array[y] = buffer;
return true;
}
Run Code Online (Sandbox Code Playgroud)
x 和 y 是应该交换的指标。
如果你想与任何类型的数组交换,那么你可以这样做:
public static bool swap<T>(this T[] objectArray, int x, int y){
// check for out of range
if(objectArray.Length <= y || objectArray.Length <= x) return false;
// swap index x and y
T buffer = objectArray[x];
objectArray[x] = objectArray[y];
objectArray[y] = buffer;
return true;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样称呼它:
string[] myArray = {"1", "2", "3", "4", "5", "6"};
if(!swap<string>(myArray, 0, 1)) {
Console.WriteLine("x or y are out of range!");
return;
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个适用于任何数组的扩展方法
public static void SwapValues<T>(this T[] source, long index1, long index2)
{
T temp = source[index1];
source[index1] = source[index2];
source[index2] = temp;
}
Run Code Online (Sandbox Code Playgroud)