我有一個練習,要求我創建2個類,每個類都會攜帶一些變量,我必須能夠通過屬性訪問和修改它們。數字錯誤值檢查,我該怎麼辦?
public class FoodItem
{
public string drinkname;
public string drinkdescription;
public int alcoholvolume;
public double drinkcost;
public FoodItem(string mfoodname)
{
foodname = mfoodname;
fooddescription = "";
peopleserved = 0;
foodcost = 0.0;
}
public string Name
{
get
{
return foodname;
}
set
{
foodname = value;
}
}
public string Description
{
get
{
return fooddescription;
}
set
{
fooddescription= value;
}
}
public int NumberServed
{
get
{
return peopleserved;
}
set
{
peopleserved = value;
}
}
public double Cost
{
get
{
return foodcost;
}
set
{
foodcost = value-((value*23)/100);
}
}
public void MaxPeopleServed()
{
if (peopleserved > 5 || peopleserved < 0)
{
Console.WriteLine("Invalid number of people served please enter a number between 1-5");
}
}
}
這是我的代碼。
練習問人口變量應該是最大值5.我可以做類似於我的方法在set屬性中做的事情嗎? 另外我應該檢查數值的錯誤值。 「在 事件中,使用set屬性輸入的數字是錯誤的,應該存儲默認值零。」這意味着構造函數是否已經初始化了這些呢? 由於提前
這個問題太基本了。只需在屬性設置器中添加一個「if」條件即可。 –