[英]How to use the properties of a class in the same class like they have values in C#
我正在嘗試使用同一類中的類的屬性與另一個值進行比較。 但是,這個屬性仍然是空的,因為我沒有那個類的實例。 請參見下面的示例。
public Zoo(string name, int capacity)
{
Name = name;
Capacity = capacity;
}
public Zoo()
{
AnimalsWhichCouldNotBeModified = new List<Animal>();
}
public List<Animal> AnimalsWhichCouldNotBeModified { get; set; }
public string Name { get; set; }
public int Capacity { get; set; }
public string AddAnimal(Animal animal)
{
// Here I have tried to use the property Capacity.
// I have also tried to use "capacity" from the constructor.
// I have also tried to create an instance of the Zoo class in the Zoo class, but it is still empty, so I am not sure if I can do that.
if (Capacity < AnimalsWhichCouldNotBeModified.Count)
{
return "The zoo is full.";
}
如何獲取示例中使用的容量(仍未實例化且為空),以便檢查動物是否超過動物園容量?
在您的第二個構造函數(不需要任何其他參數的public Zoo()
)中,您可以設置您的Capacity = 0
。
每次創建實例時,您要么使用第一個構造函數,您需要手動提供Capacity
,要么使用第二個構造函數自動將Capacity
設置為值0 。
public Zoo(string name, int capacity)
{
Name = name;
Capacity = capacity;
}
public Zoo()
{
Capacity = 0;
AnimalsWhichCouldNotBeModified = new List<Animal>();
}
public List<Animal> AnimalsWhichCouldNotBeModified { get; set; }
public string Name { get; set; }
public int Capacity { get; set; }
public string AddAnimal(Animal animal)
{
// Here I have tried to use the property Capacity.
// I have also tried to use "capacity" from the constructor.
// I have also tried to create an instance of the Zoo class in the Zoo class, but it is still empty, so I am not sure if I can do that.
if (Capacity < AnimalsWhichCouldNotBeModified.Count)
{
return "The zoo is full.";
}
}
問題是您沒有在非默認構造函數中初始化AnimalsWhichCouldNotBeModified
。 您可以將初始化添加到非默認構造函數中:
public Zoo(string name, int capacity)
{
Name = name;
Capacity = capacity;
AnimalsWhichCouldNotBeModified = new List<Animal>();
}
或從非默認值中調用默認值:
public Zoo(string name, int capacity) : this()
{
Name = name;
Capacity = capacity;
}
public Zoo()
{
AnimalsWhichCouldNotBeModified = new List<Animal>();
}
或者,第三個選項,在屬性的聲明中提供一個初始化器:
public List<Animal> AnimalsWhichCouldNotBeModified { get; set; } = new List<Animal>();
我個人更喜歡這第三個選項,除非我需要在構造函數中使用更復雜的初始化代碼。
注意Capacity
未初始化時,默認為0。 這是因為底層(編譯器生成的)支持字段被初始化為 0。默認情況下為null
的AnimalsWhichCouldNotBeModified
和Name
也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.