利用out关键字向函数传递List<T>参数遇到的问题
来源:互联网 发布:大众网络报电子版 编辑:程序博客网 时间:2024/06/06 14:03
引言
今天使用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
0 0
- 利用out关键字向函数传递List<T>参数遇到的问题
- C++函数调用时参数的传递方式遇到问题
- 参数传递及关键字params,ref,out的使用
- 利用匿名函数向setInterval中执行的函数传递参数
- ubuntu 下的C++多线程遇到的问题(2)--向线程传递参数
- 向用户控件传递参数的问题
- 向用户控件传递参数的问题
- 函数参数的传递问题
- 函数参数传递的问题
- Ajax请求传递参数遇到的问题
- springmvc 接收list参数遇到的问题
- C++函数的数组参数—向函数传递数组
- C++函数的数组参数—向函数传递数组
- C++函数的数组参数—向函数传递数组
- java向List<T>添加对象的问题
- C#方法参数传递-输出参数out关键字
- JS与PHP向函数传递可变参数的区别
- 函数参数传递问题
- 简单日程表的实现
- 编程练习题
- 静态块、动态块、构造函数、继承函数等的执行顺序
- php设置http请求头信息和响应头信息
- 提交项目到git远程仓库报错:error occurred during unpacking on the remote end: error Missing blob 261c12f4b8e2f5a
- 利用out关键字向函数传递List<T>参数遇到的问题
- LeetCode 4---Median of Two Sorted Arrays
- Python3 基础:返回函数和匿名函数
- Java基本数据类型
- curl如何发起DELETE/PUT请求
- 欢迎使用CSDN-markdown编辑器
- JS and Jquery 操作Form表单
- Linux下解决脚本错误
- cattle学航模之发动机篇