参数值类型为C#的C#中的交换方法是否无效?

问题描述

| 检查此方法
public static void Swap(ref int i,ref int j)
{
   int aux=i;
   i=j;
   j=aux;
}
比这更有效吗?
public static void Swap1(int[] a,int i,int j)
{
   int aux=a[i];
   a[i]= a[j];
   a[j]=aux;
}
我正在使用以下方法
static void Main(string[] args)
{
    int[] a = { 5,4,3,1 };
    Swap(a[1],a[2]);
    Swap(a,1,2);
}
哪种方法更有效?为什么?     

解决方法

        您的方法根本不会交换任何参数。我的意思是它将在您的方法内交换参数,但不会影响源参数的值。那是因为将值类型传递到方法中时会复制它们。这是示例:
void IncorrectSwap(int a,int b)
{
    int temp = a;
    a = b;
    b = temp;
}

void HereHappensNothing()
{
    int a = 1;
    int b = 2;
    IncorrectSwap(a,b);
    // a still = 1,and b = 2,nothing happens
}
为了使您的方法有效,您必须像这样通过引用传递值类型:
void CorrectSwap(ref int a,ref int b)
{
    int temp = a;
    a = b;
    b = temp;
}

void HereSwapHappens()
{
    int a = 1;
    int b = 2;
    CorrectSwap(ref a,ref b);
    // a = 2,and b = 1,Ok.
}
在这里,您可以阅读有关值类型以及如何使用它们的信息。 更新资料 更新之后。我认为只要值类型在通过ref传递时不被装箱,就不会在性能上有任何明显的不同。当您传递更多参数时,可能会有一些损失,但是我认为这并不重要,您不会看到任何区别。     ,        不经过
ref
将不起作用。因为您只会影响本地参数。     ,        您的代码什么都不做! 当参数通过值传递时,您将无法更改它们。 因此,要正确实现交换,您需要通过引用。