通过ref传递List <int>

Ric*_*ard 3 c# ref

可能重复:
通过ref传入对象

使用下面的代码,输出将是:

Without:
With:1
Run Code Online (Sandbox Code Playgroud)

码:

    static void Main(string[] args)
    {
        var listWithoutRef = new List<int>();
        WithoutRef(listWithoutRef);
        Console.WriteLine("Without:" + string.Join(" ", listWithoutRef));

        var listWithRef = new List<int>();
        WithRef(ref listWithRef);
        Console.WriteLine("With:" + string.Join(" ", listWithRef));
    }

    static void WithoutRef(List<int> inList)
    {
        inList = new List<int>(new int[] { 1 });
    }

    static void WithRef(ref List<int> inList)
    {
        inList = new List<int>(new int[] { 1 });
    }
Run Code Online (Sandbox Code Playgroud)

通过观察这个,我会说List上有一个List,所以无论如何都是由ref传递的,所以它们应该是一样的吗?我误解了ref关键字吗?还是我错过了别的什么?

Ree*_*sey 7

我误解了ref关键字吗?还是我错过了别的什么?

是.您没有将列表本身传递给方法,而是通过引用引用传递给列表.这可以让你改变引用(List<int>listWithRef方法中实际指的是),并把它反映.

如果不使用ref关键字,则您的方法无法更改对列表的引用 - 实际列表存储机制在任何一种情况下都不会更改.

请注意,如果您只想使用列表,则不需要这样做.List<int>.Add例如,您可以在任一方法中调用,列表将添加新项目.Ref仅需要引用类型来更改引用本身.