[英]C# - Check if integer property is set
我正在驗證一些屬性,我需要知道其他層是否設置了長整數值。
例如,這個類::
public class Person
{
public int Age {get;set;}
}
當我設置人物的新實例, 時代得到值0。但我要驗證,如果年齡分別設置,因為年齡可以為零(不,當然這種情況下)。
我想到的一個解決方案是使用int作為可空整數( public int?Age ),並在Person的構造函數中將Age設置為null。
但我試圖避免它,因為我必須更改太多的類只是為了檢查Age.HasValue並將其用作Age.Value 。
有什么建議?
Int默認初始化為0; 假設你不想使用int?
哪個適合你。 你可以檢查,或者你可以有一個標志和一個支持字段:
private int _age;
public int Age
{
get { return _age; }
set { _age = value; _hasAge = true; }
}
public bool HasAge { get { return _hasAge; } }
如上所述,您可以將其初始化為無效狀態:
private int _age = -1;
public int Age
{
get { return _age; }
set { _age = value; _hasAge = true; }
}
public bool HasAge { get { return _age != -1; } }
或者只是分解並使用int?
public int? Age { get; set; }
public bool HasAge { get { return Age.HasValue; } }
為了與代碼向后兼容,你可以將它從一個int?
沒有暴露它:
private int? _age;
public int Age
{
get { return _age.GetValueOrDefault(-1); }
set { _age = value; }
}
public bool HasAge { get { return _age.HasValue; } }
已明確設置為其默認值的字段(或自動實現的屬性)與從未設置的字段之間沒有區別。
Nullable<int>
絕對是這里的方法 - 但你需要考慮使用最干凈的API。
例如,您可能需要:
public class Person
{
private int? age;
public int Age
{
// Will throw if age hasn't been set
get { return age.Value; }
// Implicit conversion from int to int?
set { age = value; }
}
public bool HasAge { get { return age.HasValue; } }
}
這將允許您直接在假設已經設置的地方閱讀Age
- 但是當他們想要小心時測試它。
無論使用什么模式,在獲得值之前都必須有一個“設置”查詢,所以...
使用可空字段int? age
int? age
,你的的get / set屬性使用,和查詢IsAgeSet
屬性:
public class Person
{
private int? age;
public int Age {
get {return age.Value;} // will fail if called and age is null, but that's your problem......
set {age = value;}
}
public bool IsAgeSet {
get {return age.HasValue;}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.