传递列表<int>参考文献

编程入门 行业动态 更新时间:2024-10-27 18:25:54
本文介绍了传递列表<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>参考文献

本文发布于:2023-10-09 10:40:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1475514.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参考文献   列表   int   lt   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!