Passing List<int> by ref [duplicate]

会有一股神秘感。 提交于 2019-12-02 00:44:05

问题


Possible Duplicate:
passing in object by ref

With the code below, the output would be:

Without:
With:1

Code:

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

By just looking at this, I would have said that a List is on the Heap, and so is passed by ref anyway, so they should be the same? Am I misunderstanding the ref keyword? Or am I missing something else?


回答1:


Am I misunderstanding the ref keyword? Or am I missing something else?

Yes. You're not passing the list itself to the method, but rather passing the reference to the list by reference. This lets you change the reference (the List<int> that listWithRef actual refers to) within the method, and have it reflect.

Without using the ref keyword, your method can't change the reference to the list - the actual list storage mechanism is unchanged in either case.

Note that this isn't required if you just want to use the list. You can call List<int>.Add within either method, for example, and the list will get new items added to it. Ref is only required with reference types to change the reference itself.




回答2:


Yes, all of the List objects are stored on the heap either way. However, without the ref keyword, you can't reassign the inList parameter and have it affect the caller's scope. When you create a new List object, it goes on the heap as a new object, but the original reference in the caller's scope is not affected unless you use the ref keyword.

In WithoutRef, if you call methods on the existing List without redefining it, you will see that it is modified:

inList.Clear();
inList.Add(1);


来源:https://stackoverflow.com/questions/11213679/passing-listint-by-ref

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!