我有一个问题。我如何验证我的特性价格为正数,否则抛出一个新的异常。
我已经试过了,但还是不行:
public decimal Price
{
get
{
{ return this.price; }
}
set
{
if (this.price < 0)
{
throw new ArgumentException("The price should be positive!");
}
else
{
this.price = value;
}
}
}
最佳答案
现在我明白了,您正在检查属性 setter 中的支持字段,该字段具有最后一个值或默认值0
(如果尚未初始化)。使用value
相反:
private decimal price;
public decimal Price
{
get
{
{ return this.price; }
}
set
{
if (value < 0)
{
throw new ArgumentException("The price should be positive!");
}
else
{
this.price = value;
}
}
}
关于c# - 如何验证属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21426344/