C#:如何在使用“默认”存储时向属性添加前提条件
本文关键字:存储 属性 添加 条件 前提 默认 | 更新日期: 2024-10-24 22:36:25
想象一个默认属性:
class Positive {
public int Value { get; set; }
}
我想添加一个前提条件:set
值只能是正数。 是否可以在不添加成员变量样板的情况下做到这一点?
public int Value { get;
set {
if(value < 0) throw new ArgumentOutOfBoundsException();
// continue doing 'the default thing'
// instead of `value_=value`, mirrored by a change in the
// get, and adding the `int value_` member variable
}
};
不,您需要显式声明该属性才能执行所需的操作。无论如何,自动实现的属性只是较长语法的简写,因此为了向get
或set
添加其他逻辑,您必须手动编写它们。