通过引用自动传递变量

Sug*_*ime -1 c#

我有这个代码示例.它通过引用传递变量,但它不应该(我不认为).我认为通过引用传递变量是默认的.我不确定究竟要搜索什么来找到这方面的文档.

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

    namespace CS_example_2
    {
        class Program
        {
            static void Main(string[] args)
            {
                int result = setResult();

                List<string> namesResult = new List<string>();
                setResultAr(namesResult);

                for (int i = 0; i < namesResult.Count; i += 1)
                {
                    if (i == result)
                    {
                        System.Console.WriteLine("Result is " + namesResult[i]);
                        break;
                    }
                }

                System.Console.ReadKey();
            }

            static int setResult()
            {
                int result = 3;
                return result;
            }

            static void setResultAr(List<string> namesResult)
            {
                List<string> res_array = new List<string>() { "item1", "item2", "item3, "item4", "item5" };

                foreach (string s in res_array)
                {
                    namesResult.Add(s);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 6

我认为通过引用传递变量是默认的.

它不是.它通过值传递变量,它是对a的引用List<string>.由于List<string>是引用类型,您可以在方法中修改它的内容.

namesResult如果您尝试重新分配变量本身,则可以看到变量()未通过引用传递,即:

static void SetList(List<string> namesResult)
{
    List<string> res_array = new List<string>() { "item1", "item2", "item3, "item4", "item5" };
    namesResult = res_array; 
}
Run Code Online (Sandbox Code Playgroud)

执行上述操作对原始变量没有影响,因为它是按值传递的.ref List<string>但是,如果您通过引用(使用)传递它,您会看到它可以重新分配变量本身.

关于这个主题的阅读材料,Jon Skeet写了一篇关于C#中参数传递的精彩文章,详细讨论了这一点.