C#在另一个函数中覆盖字符串和字符串[]

Che*_*yos 4 c# arrays string function

我在setValues()函数中覆盖变量'arr [1]'和'test'.

arr [1]改为'BBB'

但测试不会改为'222'

输出:BBB111

但它应该是BBB222

为什么字符串测试没有更新?

public class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[10];

            arr[1] = "AAA";
            string test = "111";

            setValues(arr, test);

            int exit = -1;
            while (exit < 0)
            {

                for (int i = 0; i < arr.Length; i++)
                {
                    if (!String.IsNullOrEmpty(arr[i]))
                    {
                        Console.WriteLine(arr[i] + test);
                    }
                }
            }
        }

        private static void setValues(string[] arr, string test)
        {
            arr[1] = "BBB";
            test = "222";
        }
    }
Run Code Online (Sandbox Code Playgroud)

vrw*_*wim 5

您需要通过引用传递该字符串以便能够在方法中修改它,您可以通过添加ref关键字来执行此操作:

public class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[10];

            arr[1] = "AAA";
            string test = "111";

            setValues(arr, ref test);

            int exit = -1;
            while (exit < 0)
            {

                for (int i = 0; i < arr.Length; i++)
                {
                    if (!String.IsNullOrEmpty(arr[i]))
                    {
                        Console.WriteLine(arr[i] + test);
                    }
                }
            }
        }

        private static void setValues(string[] arr, ref string test)
        {
            arr[1] = "BBB";
            test = "222";
        }
    }
Run Code Online (Sandbox Code Playgroud)