我创建了一个类“Kleurencombinatie”,在该类中有一个带有 get 和 set 的数组。
byte[] combinatie;
public byte[] Combinatie
{
get { return combinatie; }
set { combinatie = value; }
}
我可以通过做随机数组的值
Kleurencombinatie Combo = new Kleurencombinatie();
Combo.Combinatie[0]++;
但问题是它会造成溢出。所以我的想法是验证 setter 的输入。我可以简单地使用 Modulo(%) 来做到这一点。但我不知道你会如何在二传手中做到这一点。
例如我想要的样子:
byte aantalkleuren;
public byte Aantalkleuren
{
get { return aantalkleuren; }
set { aantalkleuren = value % 7; }
//The max value of is 6 now. As soon it over 6 its starts again at 0
}
一个解决方案是,为此创建一个函数。但我认为可以在 setter 本身中执行此操作。
有什么想法吗? 谢谢!
请您参考如下方法:
如果您通过这样的属性公开原始数组,则无法拦截对其元素的写入以验证值。
但是,您可以编写自己的类来实现 indexer :
public sealed class RangeCheckedByteArray
{
public RangeCheckedByteArray(int size)
{
_data = new byte[size];
}
public byte this[int index] // This indexer ensures that values are checked.
{
get
{
return _data[index];
}
set // Nobody can set an element's value without coming through here.
{
_data[index] = (byte)(value%7);
}
}
private readonly byte[] _data;
}
用它代替字节数组,它会做你需要的:
RangeCheckedByteArray combinatie;
public RangeCheckedByteArray Combinatie
{
get { return combinatie; }
set { combinatie = value; }
}
