【发布时间】: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;
}
}
}
【问题讨论】:
-
修复编译错误:也将
swapRotations设为静态,因为你从静态方法Main调用它;我不明白你想用ref做些什么 -
这与
ref关键字无关。静态方法不能直接调用非静态方法,仅此而已。 -
如果你在谷歌上搜索你的错误信息,我相信你不用在这里问就能找到你的答案。