C# 用于交换数组中的 2 个元素的函数不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16500312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:10:44  来源:igfitidea点击:

Function for swapping 2 elements in an array doesn't work

c#swap

提问by user2373458

I am new with C# and I can't understand why this code doesn't work.

我是 C# 新手,我不明白为什么这段代码不起作用。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] sw = "ab".ToCharArray();
            swap(sw[0], sw[1]);
            string end = new string(sw);
            Console.Write(end);
        }

        static void swap(char a, char b)
        {
            char temp = a;
            a = b;
            b = temp;
        }
    }
}

What I expect on console is "ba" but I get "ab". I was able to find different approach to solve this problem but what I would like to know is what is the mistake in this code. Thanks for the help!

我在控制台上期望的是“ba”,但我得到“ab”。我能够找到不同的方法来解决这个问题,但我想知道的是这段代码中的错误是什么。谢谢您的帮助!

回答by Steven Wexler

You are passing your arguments aand bby value.
See What's the difference between passing by reference vs. passing by value?for more information.

您正在传递您的参数ab值。
请参阅按引用传递与按值传递之间的区别是什么?想要查询更多的信息。

Here are two solutions to fix your issue.

这里有两种解决方案可以解决您的问题。

//Pass by value and return the values
static Tuple<char, char> swap2(char a, char b)
{
    char temp = a;
    a = b;
    b = temp;
    return new Tuple<char, char>(a, b);
}

//Pass by reference
static void swap3(ref char a, ref char b)
{
    char temp = a;
    a = b;
    b = temp;
}

public static void Main(string[] args)
{
    char[] sw2 = "ab".ToCharArray();
    var chars2 = swap2(sw2[0], sw2[1]);
    sw2[0] = chars2.Item1;
    sw2[1] = chars2.Item2;
    //Will print "ba"
    Console.WriteLine(sw2);

    char[] sw3 = "ab".ToCharArray();
    swap3(ref sw3[0], ref sw3[1]);
    //Will print "ba"
    Console.WriteLine(sw3);
}

Here's a question about whether you should use or try to avoid the ref keyword. Aside from the simplest uses, it's often advised to avoid ref when possible. Swap falls into the category of "simplest uses," but I suggest that you try to avoid using ref in most practical situations.
When is using the C# ref keyword ever a good idea?

这是一个关于您是否应该使用或尽量避免使用 ref 关键字的问题。除了最简单的用途,通常建议尽可能避免使用 ref。Swap 属于“最简单用途”的范畴,但我建议您在大多数实际情况下尽量避免使用 ref。
什么时候使用 C# ref 关键字是个好主意?

回答by James Holderness

The problem is that the swapmethod is actually just manipulating local copies of aand b. You need to pass the arguments by reference. So you would define the swapmethod like this:

问题在于该swap方法实际上只是操作aand 的本地副本b。您需要通过引用传递参数。所以你可以这样定义swap方法:

    static void swap(ref char a, ref char b)
    {
        char temp = a;
        a = b;
        b = temp;
    }

And call it like this:

并这样称呼它:

    swap(ref sw[0], ref sw[1]);

回答by Justin Niessner

Your swap is taking two value types and swapping the values between the variables. There's nothing there that would modify the original array. You would need to modify your swap method to something like:

您的交换采用两种值类型并交换变量之间的值。没有任何东西可以修改原始数组。您需要将交换方法修改为:

static void Swap(char[] array, int a, int b)
{
    char temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}

You could then call it from Main() like:

然后你可以从 Main() 调用它,如:

Swap(array, 0, 1);

回答by Alexander Bell

It should be modified like the following (Note: in this example, ref char[] arris prefixed with refmostly for didactic purpose: array will be passed by refby default)

它应该像下面这样修改(注意:在这个例子中,ref char[] arr前缀ref主要是为了教学目的:ref默认情况下将传递数组)

namespace ConsoleApplication1
{

        class Program
        {
            static void Main(string[] args)
            {
                char[] sw = "ab".ToCharArray();
                swap(0, 1, ref sw );
                string end = new string(sw);
                Console.Write(end);
            }

            static void swap(int indexA, int indexB, ref char[] arr)
            {
                char temp = arr[indexA];
                arr[indexA] = arr[indexB];
                arr[indexB] =temp;
            }
        }
    }

回答by DragonSpit

A more generic array swap function:

一个更通用的数组交换函数:

    public static void Swap<T>(this T[] array, int indexA, int indexB)
    {
        T temp        = array[indexA];
        array[indexA] = array[indexB];
        array[indexB] = temp;
    }

Also, a generic function to swap several array elements:

此外,还有一个通用函数来交换多个数组元素:

    public static void Swap<T>(this T[] array, int indexA, int indexB, int length)
    {
        while (length-- > 0)
            Swap(array, indexA++, indexB++);
    }