[英]C# Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
[英]c# unhandled exception: object reference not set to an instance of an object
我對一組類有問題。 基本上,我創建了一個'Student'類的數組,但是由於在標題中得到了未處理的異常,因此無法將值分配給該數組中實例的任何屬性。 這是代碼:
class ControllerQueue
{
model.ModelStudent q = new model.ModelStudent();
static int capacity = 15;
model.ModelStudent[] arr = new model.ModelStudent[capacity];
int top = -1, rear = 0;
public ControllerQueue()
{
arr[0].name = "a";
arr[0].grade = 0;
}
}
我嘗試從構造函數中分配值,但仍然得到相同的結果。 現在,異常本身顯然表示我沒有實例化Student類,但是我不明白為什么會這樣說,我已經實例化了。 提前致謝。
你需要
arr[0] = new ModelStudent();
arr[0].name = "a";
arr[0].grade = 0;
您需要這樣做,因為您必須new
一個實例以將其放入索引為0的數組中
model.ModelStudent[] arr = new model.ModelStudent[capacity];
只會分配數組,但是默認情況下每個條目都是ModelStudent的默認值(null)
您需要實例化數組的成員
像這樣將項目添加到您的數組中
arr[0] = new ModelStudent();
arr[0].name = "a";
arr[0].grade = 0;
您的項目0未設置。
嘗試。
model.ModelStudent q = new model.ModelStudent();
static int capacity = 15;
model.ModelStudent[] arr = new model.ModelStudent[capacity];
int top = -1, rear = 0;
public ControllerQueue()
{
arr[0] = new model.ModelStudent();
arr[0].name = "a";
arr[0].grade = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.