将数组索引链接到变量

时间:2018-07-11 09:34:50

标签: c# .net class data-structures

我可以将数组索引链接/绑定到变量,以便当变量值更改时,它自动反映在数组上吗?

例如,

byte speed = 0x01;
Up       = new byte[] { 0xff, 0x01, 0x00, 0x10, speed, 0x00, 0x00 };
Down     = new byte[] { 0xff, 0x01, 0x00, 0x08, speed, 0x00, 0x00 }; 
Left     = new byte[] { 0xff, 0x01, 0x00, 0x04, 0x00, speed, 0x00 };
Right    = new byte[] { 0xff, 0x01, 0x00, 0x02, 0x00, speed, 0x00 };
UpSpeed = 0x04;

我有15个这样的数组。

我希望当速度值更改时,Up和Down数组将自动反映速度值。 目前,我可以这样手动设置:

public void SetSpeed()
{
    Up[4]   = speed;
    Down[4] = speed;
}

有没有办法做到这一点? 我能想到的唯一方法是实现setteer来提高速度并触发evet,然后侦听该事件并调用SetSpeed()。

1 个答案:

答案 0 :(得分:2)

设置speed为属性并更新设置器中的数组值:

byte _speed;
byte Speed
{
    get => _speed;
    set
    {
        _speed = value;
        Up[4] = value;
        Down[4] = value;
    }
}

编辑

您可以尝试以下操作:

sealed class ByteArray
{
    readonly byte[] _source;
    readonly int _speedIndex;
    readonly Func<byte> _getSpeed;

    public int Length => _source.Length;

    public byte this[int index]
    {
        get
        {
            if (index == _speedIndex)
            {
                return _getSpeed();
            }

            return _source[index];
        }
        set
        {
            if (index != _speedIndex)
            {
                _source[index] = value;
            }
        }
    }

    public ByteArray(byte[] source, int speedIndex, Func<byte> getSpeed)
    {
        // validate parameters, null check etc...

        _source = source;
        _speedIndex = speedIndex;
        _getSpeed = getSpeed;
    }

    public static explicit operator byte[] (ByteArray value) => value._source;
}

基本上是字节数组的包装器:

var up = new byte[] { 0xff, 0x01, 0x00, 0x10, speed, 0x00, 0x00 };
var upWrapper = new ByteArray(
    source: up,
    speedIndex: 4,
    getSpeed: () => speed);
相关问题