2012-08-04 20 views
1

試想一個默認屬性:C#:如何在使用「默認」存儲時爲屬性添加前提條件?

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

回答

10

不,您需要顯式聲明屬性才能執行所需的操作。無論如何,自動實現的屬性只是語法較長的簡寫,所以爲了向getset添加額外的邏輯,您必須手工編寫它們。

相關問題