1

想象一个默认属性:

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
     }
  };
4

1 回答 1

10

不,您需要显式声明该属性才能执行您需要的操作。无论如何,自动实现的属性只是较长语法的简写,因此为了向getor添加额外的逻辑,set您必须手动对其进行编码。

于 2012-08-04T14:37:20.503 回答