首页 > 解决方案 > C#:类中实例的存储;尝试获取其价值时获取 NullReferenceException

问题描述

我是 OOP 和 C# 的新手。这是我做的一个小实验:

Using System;
class A
{
    public int X { get; set; }
    public static A[] a = new A[10];
    public static int i = 0;
    public A()
    {
        this.X = -2;
    }
    public A(int x)
    {
        this.X = x;
    }
    public static void Add(A b)
    {
        if (i < 10) a[i] = b;
        i++;
        return;
    }
    public void Reveal()
    {
        Console.WriteLine(X);
    }
    public static void Show()
    {
        for (int j=0; j<=10; ++j)
        {
            a[j].Reveal();
        }
    }
}

我尝试创建一个类,它的实例存储在里面,最多 10 个对象。调用时A.Show()会抛出 NullReferenceException:“对象引用未设置为对象的实例。” 正如我猜想的那样,它必须是对象a[j]被创建,然后立即被销毁。所以它给出a[j]一个空值,因此结果?*这是我的main方法:

int val = 0;
while (val != -1)
{
    Console.Write("create a new object. new value: ");
    val = Console.ReadLine();
    A a = new A(val);
    A.Add(a);
 };
 A.Show();
 Console.ReadKey();
 return;

标签: c#oopnullreferenceexception

解决方案


请注意循环的上限条件:

 for (int j=0; j<=10; ++j)
    {
        a[j].Reveal();
    }

数组 a 分配了 10 个项目,但此代码显示您有 11 个项目从 0 到 10 开始,因此将其更改为略低于 10。并且还尝试比较所以正确的代码可以如下:

  public static void Show()
         {
        for (int j = 0; j < 10; ++j)
        {
            a[j]?.Reveal();//Or if(a[j] != null)
        }
    }

并对读取客户端输入的行进行修改,必须如下:

      val = int.Parse(Console.ReadLine());//If you are sure that the input 

真正可转换为 int,或

       int.TryParse(Console.ReadLine() , out int value);
            if(value != 0)
            {
                val = value;
                A a = new A(val);
                A.Add(a);
            }
            else
            {
                throw new Exception();
            }

推荐阅读