利用out关键字向函数传递List参数遇到的问题
引言
今天使用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上也有过相关问题的讨论:
总结分析
这个问题总感觉解决的不彻底,没有搞清楚myArray = null 与 myArray =new List<T>;这里还有什么问题存在。这次仅仅作为自己的总结,下次有新的想法再补充进来。
附上一些参考资料:
下一篇:
如何获取淘宝APP原数据现场教学