在数组上使用'ref'关键字

Jos*_*hua 1 c# arrays ref

我理解为什么ref在编写函数来交换两个值时应该使用,但我不知道如何在整个数组上使用该关键字.这听起来很愚蠢,但我已经尝试将关键字粘贴到我可能想到的任何地方(例如在参数之前,变量之前等等)但是我仍然得到以下错误:

错误1非静态字段,方法或属性'Swap.Program.swapRotations(int [])'需要对象引用

这是我到目前为止所做的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Swap
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] A = {0, 1, 2, 3, 4, 5, 6, 7};

            swapRotations(A);

            for (int i = 0; i < A.Length; i++)
                Console.WriteLine(A[i]);

            Console.WriteLine("\nPress any key ...");
            Console.ReadKey();
        }

        private void swapRotations(int[] intArray)
        {
            int bone1Rot = intArray[3];
            int bone2Rot = intArray[5];

            // Make the swap.
            int temp = bone1Rot;
            bone1Rot = bone2Rot;
            bone2Rot = temp;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

The*_*der 10

简单的改变:

private void swapRotations(int[] intArray);
Run Code Online (Sandbox Code Playgroud)

至:

private static void swapRotations(int[] intArray);
Run Code Online (Sandbox Code Playgroud)

问题是因为调用方法static所以它使用的任何方法都需要有一个引用它们的对象或者它们本身是静态的.

另请参阅@ ASh关于如何swapRotations"正确" 执行此功能的答案.注意我说的正确,因为可能仍然会IndexOutOfRange抛出异常.为了正确和通用地做到这一点,我会按照以下方式做一些事情:

private static void SwapIndexes(int[] array, int index1, int index2)
{
    if (index1 >= array.Length || index2 >= array.Length)
        throw new Exception("At least one of the indexes is out of range of the array");

    int nTemp = array[index1];
    array[index1] = array[index2];
    array[index2] = nTemp;
}
Run Code Online (Sandbox Code Playgroud)