2013-04-14 76 views
2
的值

擁有內部具有多個channels的課程。對於每個通道,我們可以讀取或寫入相同的值。設置並獲得來自課程

int channel = 2; 
var value = obj.GetValue(channel); 
obj.SetValue(channel, value + 1); 

實現這一切GettersSetters混淆了我自認爲C#允許有properties。有沒有更好的方法來做到這一點?

回答

6

語義上「更好」的方式可能是實施indexer

舉個例子,使用您有內部Channel對象的事實:

partial class MyClass 
{ 
    public Channel this[int channel] 
    { 
     get 
     { 
      return this.GetChannelObject(channel); 
     } 

     /* 
     * You probably don't want consumers to be able to change the underlying 
     * object, so I've commented this out. You could also use a private 
     * setter instead if you want to internally make use of the indexing 
     * semantic, but since you're most likely just wrapping an IList<Channel> 
     * anyway, you probably don't need it. 
     * 
     * set 
     * { 
     *  this.SetChannelObject(channel); 
     * } 
     */ 
    } 
} 

然後,你可以簡單地做:

int channel = 2; 
var value = obj[channel].ValueA; 
obj[channel].ValueA = value + 1; 
+0

謝謝您的例子。這允許設置1個值。如何設置多個?在索引器上返回一個特殊的'Channel'類型? – Razer

+1

@Razer你是什麼意思?就像爲通道'1'到'5'設置相同的值? –

+0

不,請考慮每個頻道都有「ValueA」和「ValueB」。如何設置它們?公共類Channel {public int ValueA {get; set;} public int ValueB {get;設置;}}? – Razer