[英]creating a property to store an instance c#
我認為這些問題很簡單,直到我意識到它所引用的TableOrder實例包含兩個屬性(一種食物和一種飲料)。
所以我的問題是,這是否意味着我需要存儲兩個屬性,還是為TableOrder創建一個新屬性? (我懷疑后者,因為該類稱為TableOrder。
我已經醒了24小時,現在一直在努力理解這些問題。
任何幫助將不勝感激。
public class TableBill
{
// the first way of initializing - by just passing the table number
public TableBill(int tableNumber)
{
this.TableNumber = tableNumber;
}
// second option will use the first constructor to set table number (the ':this()' line)
// and then set the order
public TableBill(int tableNumber, TableOrder order)
: this(tableNumber)
{
this.Order = order;
}
// the table number property has a private setter, so it will only be set
// from the constructors.
public int TableNumber { get; private set; }
// a completely public property for setting the order
public TableOrder Order { get; set; }
}
您還可以選擇使用可選參數將兩個構造函數合並為一個:
public TableBill(int tableNumber, TableOrder order = null)
{
this.TableNumber = tableNumber;
this.Order = order;
}
當第一個問題談到On initialisation
,它可能意味着使用構造函數。
您的課程可能是這樣的:
public class TableBill
{
public Order Order
{
get
{
return this._order;
}
set
{
this._order = value;
}
}
private Order _order = null;
public TableBill(int tableNumber)
{
// ...
}
public TableBill(int tableNumber, Order order)
{
// check for nulls etc...
// ...
this.Order = order;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.