C#:如何在使用"默认"存储时为属性添加前置条件?

xto*_*ofl 1 c# properties preconditions

想象一个默认属性:

class Positive {
  public int Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想补充一个先决条件: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
     }
  };
Run Code Online (Sandbox Code Playgroud)

And*_*are 10

不,您需要明确声明属性以执行您需要的操作.自动实现的属性都只是无论如何较长语法速记,所以为了额外的逻辑添加到get或set您必须手动进行编码.