有一个内部有几个channels
的类。对于每个通道,我们可以读取或写入相同的值。
int channel = 2;
var value = obj.GetValue(channel);
obj.SetValue(channel, value + 1);
实施所有这些Getters
和Setters
让我感到困惑,因为C#
允许properties
。有没有更好的方法来做到这一点?
答案 0 :(得分: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;