简体   繁体   English

具有静态类属性的NullReferenceException

[英]NullReferenceException with static class property

I have a static class that looks like this: 我有一个看起来像这样的静态类:

namespace Argus
{
    static class Argus
    {
        public static List<Branch> myArgus;
    }
}

and elsewhere in my code I have this: 在我的代码的其他地方,我有这个:

// Add this branch to myArgus
Argus.myArgus.Add(branch);

When I run the code, I get this error: 运行代码时,出现以下错误:

Object reference not set to an instance of an object. 你调用的对象是空的。

I have verified that branch is valid (it's an object of the Branch class), and have no idea what could be wrong here. 我已经验证了branch是有效的(它是Branch类的对象),并且不知道这里可能有什么问题。 I'm trying to read branch data in from a text file. 我正在尝试从文本文件中读取分支数据。

You need to instantiate it; 您需要实例化它。 it's default value is null otherwise: 它的默认值为null,否则:

public static List<Branch> myArgus = new List<Branch>();

您必须实例化myArgus

public static List<Branch> myArgus = new List<Branch>();

You are never allocating memory for myArgus . 您永远不会为myArgus分配内存。 Of course it's null . 当然是null

public static List<Branch> myArgus = new List<Branch>();

You must always make references point to allocated objects in memory, otherwise they cannot be used. 您必须始终使引用指向内存中已分配的对象,否则无法使用它们。 Trying to invoke operations on references not pointing to allocated memory will result in NullPointerException . 尝试对未指向分配的内存的引用调用操作将导致NullPointerException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM