拆分然后组合byte []

时间:2015-01-13 15:03:38

标签: c# arrays bytearray

所以我要做的是将一个byte []保存到我的数据库中。如果要将字节长发送到数据库,我想将其拆分为两个大小一半的字节。但是我做错了,因为当我检查splittet字节组合等于原始字节时是不是。

我的代码如下所示:

    public File Add(File item)
    {
        try
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            db.Entry(item).State = EntityState.Added;
            db.SaveChanges();
        }
        catch
        {
            File firstHalf = item;
            File lastHalf = item;
            firstHalf.@byte = item.@byte.Take(item.@byte.Length / 2).ToArray();
            lastHalf.@byte = item.@byte.Skip(item.@byte.Length / 2).ToArray();

            byte[] rv = new byte[firstHalf.@byte.Length + firstHalf.@byte.Length];
            System.Buffer.BlockCopy(firstHalf.@byte, 0, rv, 0, firstHalf.@byte.Length);
            System.Buffer.BlockCopy(lastHalf.@byte, 0, rv, firstHalf.@byte.Length, lastHalf.@byte.Length);

            if(rv == item.@byte)
            {
                Add(firstHalf);
                Add(lastHalf);
            }
        }

        return item;
    }


修改

public partial class File
{
    public int C_id { get; set; }
    public string name { get; set; }
    public byte[] @byte { get; set; }
    public int file_id { get; set; }
    public int fk_folder { get; set; }
    public int fk_profile { get; set; }
}

2 个答案:

答案 0 :(得分:3)

比较使用rv.SequenceEqual(item.@byte)(或循环)当前你想看看它们是否是相同的引用(它们不是)。

另外,不要使用Exception来控制流程!

答案 1 :(得分:2)

问题从这里开始:

File firstHalf = item;
File lastHalf = item;
firstHalf.@byte = item.@byte.Take(item.@byte.Length / 2).ToArray();

您只是在第一行创建了对item的新引用,因此在第三行中您将损坏原始 @byte

您需要使用item的深层副本。

一种可能的方法 - 在Clone类中创建File方法,该方法将返回带有复制fiedls的File的新实例,而不是File firstHalf = item;它将{ {1}}

这是我想到的第一种方法,可能不是最好的方法。事实上,我现在无法估计 - 你真的需要你File firstHalf = item.Clone();的两个精确副本 - 可能这个逻辑应该被重构。