当使用列表< T>时,对象引用未设置为对象的实例。在C#中 [英] Object reference not set to an instance of object when using a List<T> in C#

查看:346
本文介绍了当使用列表< T>时,对象引用未设置为对象的实例。在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码片段会产生编译错误:

I have the following code snippet that produces a compilation error:

public List<string> batchaddresses;

public MapFiles(string [] addresses)
{
    for (int i = 0; i < addresses.Count(); i++)
    {
        batchaddresses.AddRange(Directory.GetFiles(addresses[i], "*.esy"));
    }
}

当我尝试使用 List< T> .AddRange()方法:

I get an error when I try to use the List<T>.AddRange() method:

Object reference not set to an instance of an object

我做错了什么?

推荐答案

在哪里batchaddresses初始化?

Where is batchaddresses initialized?

声明变量不够。您必须初始化它,如下所示:

Declaring the variable does not suffice. You must initialize it, like so:

// In your constructor
batchaddresses = new List<string>();

// Directly at declaration:
public List<string> batchaddresses = new List<string>();

这篇关于当使用列表&lt; T&gt;时,对象引用未设置为对象的实例。在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆