[英]Filling and printing out an array of class type
好的,所以我不太擅長解釋,但基本上我有一個簡單的 class - 讓我們這樣說:
class Dog
{
public String Name { get; set; }
public String Breed { get; set; }
}
然后我有另一個 class:
static class DogData
{
static public Dog[] Dogs
{
get
{
//Dog[] Dogs = new Dog[2]; - unnecessary, as pointed out by helpful Samaritans
ResetDogData();
return _dogs;
}
set { }
}
static public Dog[] _dogs;
static private void ResetDogData()
{
Dog[] _dogs = new Dog[2];
if (_dogs[0] == null)
{
_dogs[0] = new Dog();
_dogs[0].Name = "Johny";
_dogs[0].Breed = "German Shepard";
}
if (_dogs[1] == null)
{
_dogs[1] = new Dog();
_dogs[1].Name = "Sally";
_dogs[1].Breed = "Alaskan Malamute";
}
}
想法是讓 Dogs 數組填充來自控制台的輸入,如果數組元素是 null - 從 ResetDogData() 獲取其數據。 但在嘗試這樣做之前,我想測試 ResetDogData() 是否有效。
事情就是這樣 - 每次我嘗試打印出來時,我要么得到“對象引用未設置為對象的實例”,要么,如果它編譯,則根本沒有打印出來(取決於我嘗試的方式)。 所以我想知道我的代碼是否完全錯誤,或者我只是缺少使用 arrays 的一些基礎知識(例如,我的錯誤是我試圖打印出數組的方式)。
如果有人能告訴我兩者中的哪一個,以及實現我想要的正確方法是什么,我將不勝感激。
ResetDogData
沒有修改類級別的_dogs
成員 - 它是創建一個本地_dogs
變量,填充它,然后什么都不做。
要重置 class 成員的數據,請更改
Dog[] _dogs = new Dog[2];
至
_dogs = new Dog[2];
在ResetDogData
內
此外,您可以擺脫if
a,因為新創建的數組將始終使用null
進行初始化:
static private void ResetDogData()
{
_dogs = new Dog[2];
_dogs[0] = new Dog();
_dogs[0].Name = "Johny";
_dogs[0].Breed = "German Shepard";
_dogs[1] = new Dog();
_dogs[1].Name = "Sally";
_dogs[1].Breed = "Alaskan Malamute";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.