C# 从类中设置并获取值
具有内部具有多个C# 从类中设置并获取值,c#,.net,C#,.net,具有内部具有多个通道的类。对于每个通道,我们可以读取或写入相同的值 int channel = 2; var value = obj.GetValue(channel); obj.SetValue(channel, value + 1); 实现所有这些getter和setter让我感到困惑,因为C允许拥有属性。有更好的方法来实现这一点吗?语义上“更好”的方法可能是实现一个 例如,使用具有内部通道对象的事实: partial class MyClass { public Chann
通道的类。对于每个通道,我们可以读取或写入相同的值
int channel = 2;
var value = obj.GetValue(channel);
obj.SetValue(channel, value + 1);
实现所有这些getter
和setter
让我感到困惑,因为C
允许拥有属性。有更好的方法来实现这一点吗?语义上“更好”的方法可能是实现一个
例如,使用具有内部通道对象的事实:
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);
* }
*/
}
}
谢谢你的例子。这允许设置1个值。如何设置多于1个?在索引器上返回一个特殊的频道
类型?@Razer你是什么意思?如为通道<代码> 1 < /代码>通过<代码> 5 < /代码>设置相同值吗?不,考虑每个通道都有<代码> Value和<代码> ValueB< <代码>。如何设置它们?公共类通道{public int ValueA{get;set;}public int ValueB{get;set;}}}?@Razer也许您应该定义一个通道
对象,然后它具有这些单独的属性。索引器可以返回此对象,您可以对其设置值:obj[channelNumber].ValueB=9代码>@ChrisSinclair这是我在第一条评论中的想法:)
int channel = 2;
var value = obj[channel].ValueA;
obj[channel].ValueA = value + 1;