一个帮助访问大块内存的类

时间:2016-05-16 21:48:12

标签: c# oop design-patterns

我需要一个类来帮助我访问一块内存

到目前为止,我有这个

class ABSet
{
    private byte[] _raw;
    public ABSet(byte[] RawData)
    {
        _raw=RawData;
    }
    public double A
    {
        get
        {
            return BitConverter.ToDouble(_raw, 2);
        }
     }
     public double B
     {
         get
         {
             return BitConverter.ToDouble(_raw, 10);
         }
     }
}

现在我想做这样的事情

class ABSetCollection
{
    private byte[] _raw;
    public ABSetCollcetion(byte[] RawData)
    {
        _raw=RawData;
    }
    public ABSet this[int index]
    {
        get
        {
            // This Part Is What I Want To Figure Out
        }
     } 
}

我知道我可以放return new ABSet(_raw);,但我觉得必须有一个需要较少动态分配的解决方案。

P.S。我想使用属性的原因是因为我在GUI中绑定了它们

1 个答案:

答案 0 :(得分:0)

不是仅仅接受一个字节数组,而是更改它以便获得偏移量。然后你就能让它发挥作用。

class ABSet
{
    public const int ABSetSize = 20; // or whatever the size

    private readonly byte[] _data;
    private readonly int _offset;
    public ABSet(byte[] data, int offset = 0)
    {
        _data = data;
        _offset = offset;
    }

    const int AOffset = 2;
    public double A => BitConverter.ToDouble(_data, _offset + AOffset);

    const int BOffset = 10;
    public double B => BitConverter.ToDouble(_data, _offset + BOffset);
}

class ABSetCollection
{
    private readonly byte[] _data;
    private readonly int _offset;
    public ABSetCollection(byte[] data, int offset = 0)
    {
        _data = data;
        _offset = offset;
    }

    public ABSet this[int index] => new ABSet(_data, _offset + index * ABSet.ABSetSize);
}