![](/img/trans.png)
[英]NullReferenceException error in Unity when trying to get data from a static class
[英]C#: Storage of instances in the class; get NullReferenceException when trying to get theirs value
我是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;
請注意循環的上限條件:
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();
}
您在分配a[i]
之前先遞增i
,所以a[0]
為null,因為它將始終從1開始初始化a
。
嘗試將add方法更改為此:
public static void Add(A b)
{
if (i < 10)
{ //braces are important for readability
a[i] = b;
}
i++;
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.