【问题标题】:Using the 'ref' keyword on an array在数组上使用 'ref' 关键字
【发布时间】:2016-02-22 21:53:48
【问题描述】:

我明白为什么在编写交换两个值的函数时应该使用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;
        }
    }
}

【问题讨论】:

标签: c# arrays ref


【解决方案1】:

简单就是改变:

private void swapRotations(int[] intArray);

到:

private static void swapRotations(int[] intArray);

问题是因为调用方法是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;
}

【讨论】:

  • 如果你真的想正确地做到这一点,不要忘记index1&lt;0index2&lt;0案例; 一般会是这样的:void SwapIndexes&lt;T&gt;(T[] array, int index1, int index2) { T nTemp = array[index1]; array[index1] = array[index2]; array[index2] = nTemp; }
  • @ASh 我并没有批评你的方法,只是展示了 一些 可以进行的安全检查,OP 可以再开发
【解决方案2】:

ArraysReference 类型。所以不需要使用ref 关键字来传递数组。您的问题不在ref 关键字中,而是您必须仅调用静态方法中的静态方法。 例如:

    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 static void swapRotations(int[] intArray)
    {           
        // Make the swap.
        int temp = intArray[3];  
        intArray[3] = intArray[5];
        intArray[5] = temp;
    }

【讨论】:

  • 值/引用类型和按值/引用传递是完全不同的主题。这不是重点
【解决方案3】:

swap 方法不起作用,因为你根本不改变数组

ref中不需要,只需设置数组元素

private void swapRotations(int[] intArray)
{
    int temp = intArray[3];
    intArray[3] = intArray[5];
    intArray[5] = temp;
}

【讨论】:

    猜你喜欢
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 2012-11-19
    • 2013-12-31
    • 2011-06-16
    • 1970-01-01
    • 2010-12-31
    相关资源
    最近更新 更多