利用out关键字向函数传递List<T>参数遇到的问题
2016-12-28 22:35
495 查看
引言
今天使用out关键字向函数传递List<T>参数遇到了一点问题,做个记录。之前只是大概了解out关键字就是作为引用传递。
遇到的问题
今天先写了如下代码:
定位问题出现在myArray = null;
查阅了资料获悉,不必初始化作为 out 参数传递的变量,必须在方法返回之前为 out 参数赋值。
代码修改为:
当然也可以删除代码片段1中的out关键字,通过值传递可以避免这个问题。
stackoverflow上也有过相关问题的讨论:List<T> as 'out' parameter causes an error. Why?
总结分析
这个问题总感觉解决的不彻底,没有搞清楚myArray = null 与 myArray =new List<T>;这里还有什么问题存在。这次仅仅作为自己的总结,下次有新的想法再补充进来。
附上一些参考资料:
C#基础:ref和out的区别
Passing Arrays Using ref and out
List Count vs List null condition, change results
今天使用out关键字向函数传递List<T>参数遇到了一点问题,做个记录。之前只是大概了解out关键字就是作为引用传递。
遇到的问题
今天先写了如下代码:
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static public void Main() { List<int> myArray = new List<int>(); FillArray(out myArray); Console.WriteLine("List.count: " + myArray.Count); Console.ReadLine(); } static public void FillArray(out List<int> myArray) { myArray = null; myArray.Add(1); // 这里运行会出错 } } }运行到myArray.Add(1);处会报错
定位问题出现在myArray = null;
查阅了资料获悉,不必初始化作为 out 参数传递的变量,必须在方法返回之前为 out 参数赋值。
代码修改为:
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Test1 { static public void Main() { //List<int> myArray = new List<int>(); // 这里不需要对myArray进行初始化 List<int> myArray = null; FillArray(out myArray); Console.WriteLine("List.count: " + myArray.Count); Console.ReadLine(); } static public void FillArray(out List<int> myArray) { myArray = new List<int>(); // 需要对myArray重新分配存储空间 //myArray = null; myArray.Add(1); // 这里运行会出错 } } }
当然也可以删除代码片段1中的out关键字,通过值传递可以避免这个问题。
stackoverflow上也有过相关问题的讨论:List<T> as 'out' parameter causes an error. Why?
总结分析
这个问题总感觉解决的不彻底,没有搞清楚myArray = null 与 myArray =new List<T>;这里还有什么问题存在。这次仅仅作为自己的总结,下次有新的想法再补充进来。
附上一些参考资料:
C#基础:ref和out的区别
Passing Arrays Using ref and out
List Count vs List null condition, change results
相关文章推荐
- C#中out保留字用法实例分析
- C#编程中使用ref和out关键字来传递数组对象的用法
- 在MySQL中创建带有IN和OUT参数的存储过程的方法
- ref与out之间的区别深入解析
- 一看就懂:图解C#中的值类型、引用类型、栈、堆、ref、out
- C#中out与ref的区别实例解析
- 浅谈jQuery hover(over, out)事件函数
- ASP.NET Ref和Out关键字区别分析
- Git使用小坑 Out of memory错误的解决方法
- mysqld-nt: Out of memory (Needed 1677720 bytes)解决方法
- nodejs 通过nginx后出现响应慢的解决方法
- “菜刀女”火爆网络 凤姐们OUT该洗洗睡了
- out 参数修饰符(C# 参考)
- C#学习基本概念之关键字--ref与out
- C#学习经典方法之(八)---XmlNode.OuterXml属性
- C#如何一个方法实现多个返回值(out和ref的区别)
- 异常:pointerIndex out of range
- android aidl in out
- 【黑马程序员】C#之out、ref,
- 详解JSP九大内置对象