C# C:在使用“默认”存储时,如何向属性添加前提条件?

C# C:在使用“默认”存储时,如何向属性添加前提条件?,c#,properties,preconditions,C#,Properties,Preconditions,设想一个默认属性: class Positive { public int Value { get; set; } } 我想补充一个先决条件:设定值只能为正值。是否可以在不添加成员变量样板的情况下执行此操作 public int Value { get; set { if(value < 0) throw new ArgumentOutOfBoundsException(); // continue doing 'the default

设想一个默认属性:

class Positive {
  public int Value { get; 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添加额外的逻辑,您必须手动对它们进行编码。

否,您需要显式声明属性才能执行所需操作。自动实现的属性只是较长语法的简写,因此为了向get或set添加额外的逻辑,必须手动编写它们