C#Custom Chain,添加CRC字节

时间:2017-09-11 15:12:15

标签: c# chain

我想编写一个方法链来添加带有byte []的CRC(2字节)。 有了网络资源,我写这个。但不工作...... 知识少,我不知道为什么...... 请帮帮我..

public byte[] AddCrc<T>(this byte[] x)
{
    if (x == null) throw new ArgumentNullException("x");
    int oldLen = x.Length;
    byte[] y = makeCrc2bytes(x, oldLen);
    Array.Resize<byte>(ref x, x.Length + y.Length);
    Array.Copy(y, 0, x, oldLen, y.Length);
    return x;
}

......示例......

byte[] buffer = new byte[6];
    buffer[0] = 0x01;
    buffer[1] = 0x02;
    buffer[2] = 0x03;
    buffer[3] = 0x04;
    buffer[4] = 0x05;
    buffer[5] = 0x06;
 byte[] buffer2 = buffer.AddCrc();  // Now work.

1 个答案:

答案 0 :(得分:1)

由于您未传递未使用的类型参数,因此遇到编译器错误。从.AddCrc(...)方法中删除它。顺便说一句,你传递给.AddCrc()的数组是按值的,因此它不会被扩展。 Array.Resize<T>(...)创建一个新数组,将原始值复制到该数组中,然后更改传递给函数的引用(ref)。

你也可以这样做......

public static byte[] AddCrc(this byte[] input) //type param not used.
{
    if (input == null) throw new ArgumentNullException("input");

    var crc = makeCrc2bytes(input, input.Length);

    var result = new byte[input.Length + crc.Length];
    Array.Copy(input, 0, result, 0, input.Length);
    Array.Copy(crc, 0, result, input.Length, crc.Length);
    return result;
}