2

有一个内部有几个channels. 对于每个通道,我们可以读取或写入相同的值。

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

实现所有这些Getters并让Setters我感到困惑,因为这C#允许拥有properties. 有没有更好的方法来做到这一点?

4

1 回答 1

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;
于 2013-04-14T16:12:31.923 回答