用于交换数组中的 2 个元素的函数不起作用 [英] Function for swapping 2 elements in an array doesn't work

查看:41
本文介绍了用于交换数组中的 2 个元素的函数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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!

推荐答案

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

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

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

然后这样称呼它:

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

这篇关于用于交换数组中的 2 个元素的函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆