我對我的 IF 陳述句有疑問,它不起作用:DI 想檢查 ID、年齡和薪水,如果它大于 0,但我的代碼只是忽略它,想將 0 更改為某些含義,例如 - 如果年齡<= 0 set age = 21 etc 很高興看到您的答案。謝謝!
class Person
{
private int _age;
private string _firstName;
private string _lastName;
private int _id;
public Person(int age, string firstName, string lastName, int id)
{
_age = age;
_firstName = firstName;
_lastName = lastName;
_id = id;
}
public int GetAge()
{
return _age;
}
public void SetAge(int age)
{
if (_age == 0)
_age = 21;
else
_age = age;
}
public int GetId()
{
return _id;
}
public void SetId(int id)
{
if (id > 0)
_id = id;
else
_id = 1;
}
public void Print()
{
Console.WriteLine("Age: {0}\tFirst name: {1}\tLast name: {2}\tID: {3}", this._age, this._firstName, this._lastName, this._id);
}
}
class TestInheritence
{
public static void Main(string[] args)
{
Employe[] employees = new[]
{
new Employe(21, "John", "Watson", 0)
};
employees[0].Print();
}
}
uj5u.com熱心網友回復:
這是一個錯誤:
public void SetAge(int age)
{
if (_age == 0) //<-- This should be age==0, not _age
_age = 21;
else
_age = age;
}
您可以從使用屬性中受益。或者按照公認的答案建議實際使用您的 Set 方法。
uj5u.com熱心網友回復:
這是因為您不使用具有 if 陳述句的設定器,而是直接設定變數。
所以代替
_age = age;
你應該使用
setAge(age);
uj5u.com熱心網友回復:
嘗試使用您在更新變數時撰寫的 setter,以便它進入代碼中的條件陳述句。此外,年齡的 if 陳述句應該是:if(age <= 0) _age = 21;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/383733.html
上一篇:使用指標和strncat時,visualstudio觸發斷點
下一篇:無法將vsix安裝到VisualStudio2019-Android設備管理器的版本低于VisualStudio的要求
