利用out关键字向函数传递List<T>参数遇到的问题

引言

今天使用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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值