从类中设置和获取值

本文关键字:获取 设置 | 更新日期: 2023-09-27 18:09:20

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

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

实现所有这些GettersSetters让我困惑,因为C#允许有properties。是否有更好的方法来做到这一点?

从类中设置和获取值

语义上"更好"的方法可能是实现一个索引器。

作为一个例子,使用内部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;