public class Person
{
public string FullName { get; set; }
public int? PhoneNumber { get; set; }
public int? CarQTY { get; set; }
}
如果有人没有完全填充对象,我想抛出异常。例如,如果 fullName、phoneNumber 或 carQTY 为 null,我想在 get 方法上引发异常。
我真的必须这样做吗?
public class Person
{
string _FullName;
int? _PhoneNumber;
int? _CarQTY;
private Boolean IsValid()
{
Boolean condition = true;
condition = (FullName != null) && (PhoneNumber != null) && (CarQTY != null);
return condition;
}
public string FullName
{
get
{
if (!IsValid()) throw new System.ArgumentException("Parameter cannot be null", "fullName is null");
return _FullName;
}
set
{
_FullName = value;
}
}
public int? PhoneNumber
{
get
{
if (!IsValid()) throw new System.ArgumentException("Parameter cannot be null", "phoneNumber is null");
return _PhoneNumber;
}
set
{
_PhoneNumber = value;
}
}
public int? CarQTY
{
get
{
if (!IsValid()) throw new System.ArgumentException("Parameter cannot be null", "carQTY is null");
return _CarQTY;
}
set
{
_CarQTY = value;
}
}
}
正如评论中所建议的,强制通过构造函数创建对象是最有效的方法:
public class Person
{
public string FullName { get; private set; }
public int PhoneNumber { get; private set; }
public int CarQTY { get; private set; }
public Person(string fullName, int phone, int carQty){
FullName = fullName;
PhoneNumber = phone;
CarQTY = carQty;
}
}
如果您希望允许在创建对象后对其进行修改,那么 setter 也可以是公共的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)