gpt4 book ai didi

c# - 在数组上使用 'ref' 关键字

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:59 25 4
gpt4 key购买 nike

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

Error 1 An object reference is required for the non-static field, method, or property '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;
}
}
}

最佳答案

简单的改变:

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;
}

关于c# - 在数组上使用 'ref' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com