c#在静态类中连接静态数组

问题描述 投票:0回答:1

我甚至不确定如何调用我想要实现的内容但是......可能代码会解释它。

基本上,我想创建帧命令作为一些静态定义的数组的组合。

我想做这样的事情:

Command = ConcatArrays(commandPart1,commandPart2,commandPart2)

但它在ConcatArrays中失败,因为列表元素似乎为null。

并在外部使用如下:

Frame.Frame1.Command

我从这里拿到了ConcatArrays:https://stackoverflow.com/a/3063504/15872

这样的事情可能吗?

非常感谢任何帮助,我对C#很新。

public static class Frame
{

public class RequestModel
{
    public byte[] Command { get; set; }
    public int ReceiveLength { get; set; }
}

public static RequestModel Frame1 = new RequestModel
{
    Command = ConcatArrays(commandPart1, commandPart2, commandPart2)
    ReceiveLength = 16,
};

public static RequestModel Frame2 = new RequestModel
{
    Command = ConcatArrays(commandPart1, commandPart3)
    ReceiveLength = 16,
};

private static byte[] commandPart1 = new byte[] { 0x1, 0x02 };
private static byte[] commandPart2 = new byte[] { 0x3, 0x4 };
private static byte[] commandPart3 = new byte[] { 0x5, 0x6 };

public static T[] ConcatArrays<T>(params T[][] list)
{
    var result = new T[list.Sum(a => a.Length)];
    int offset = 0;
    for (int x = 0; x < list.Length; x++)
    {
        list[x].CopyTo(result, offset);
        offset += list[x].Length;
    }
    return result;
}

}
c# arrays constructor static concatenation
1个回答
2
投票

你不能在下面引用静态成员。例如,Frame1成员引用静态类下面定义的commandPart1静态成员。

一种解决方法是在引用的位置上方定义静态成员。以下测试通过:

    [Test]
    public void Frame1CommandShouldIncludeParts1and2and2()
    {
        var expected = new byte[] {0x1, 0x02, 0x3, 0x4, 0x3, 0x4};
        var actual = Frame.Frame1.Command;
        Assert.AreEqual(expected, actual);
    }

    [Test]
    public void Frame2CommandShouldIncludeParts1and3()
    {
        var expected = new byte[] {0x1, 0x02, 0x5, 0x6};
        var actual = Frame.Frame2.Command;
        Assert.AreEqual(expected, actual);
    }

    public class RequestModel
    {
        public byte[] Command { get; set; }
        public int ReceiveLength { get; set; }
    }

    public static class Frame
    {
        private static readonly byte[] CommandPart1 = { 0x1, 0x02 };
        private static readonly byte[] CommandPart2 = { 0x3, 0x4 };
        private static readonly byte[] CommandPart3 = { 0x5, 0x6 };

        public static RequestModel Frame1 = new RequestModel
        {
            Command = ConcatArrays(CommandPart1, CommandPart2, CommandPart2),
            ReceiveLength = 16
        };
        public static RequestModel Frame2 = new RequestModel
        {
            Command = ConcatArrays(CommandPart1, CommandPart3),
            ReceiveLength = 16
        };

        private static T[] ConcatArrays<T>(params T[][] list)
        {
            var result = new T[list.Sum(a => a.Length)];
            int offset = 0;
            for (int x = 0; x < list.Length; x++)
            {
                list[x].CopyTo(result, offset);
                offset += list[x].Length;
            }
            return result;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.