传递列表<int>参考文献 [英] Passing List&lt;int&gt; by ref

查看:69
本文介绍了传递列表<int>参考文献的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
通过引用传入对象

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

With the code below, the output would be:

Without:
With:1

代码:

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

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

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?

推荐答案

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

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

是的.您不是将列表本身传递给方法,而是通过引用传递对列表的引用.这使您可以更改方法中的引用(listWithRef 实际引用的 List),并使其反映.

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.

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

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.

请注意,如果您只想使用列表,则这不是必需的.例如,您可以在任一方法中调用 List.Add,然后列表将添加新项目.只有引用类型需要 Ref 才能更改引用本身.

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.

这篇关于传递列表<int>参考文献的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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