2

(对于所见即所得,我的意思是决定写什么如何写,而不是微软或谷歌的某个人)(好吧......从技术上讲,我什么都不决定......几年前编程的人决定了,我只能问我要跳多高)

今天我觉得有点愚蠢,但我已经浪费了两个小时来寻找解决方案:-(。

现在...

我有一个二进制协议。它是基于 C 的,所以它就像查看一个 C 结构,其中定义了机器的字节序(幸运的是,它与“本地”字节序相同),定义了各种类型的大小,定义了数据结构对齐,结构的布局已定义,字符串是已知编码的固定字符数组......一切都已定义!unsafe struct当您使用时,一切都与 C# 非常相似,并且您对使用数组修饰符[(LayoutKind.Explicit)]不是很挑剔。fixed现在我需要在 C# 中对其进行序列化/反序列化...我环顾四周,但找不到任何东西...我错过了什么?在你问之前,我知道BinaryFormatter,但它对我来说还不够 WYSIWYG ......BinaryFormatter实现了它的格式化语言。是的,我知道BitConverter(事实上​​它没有实现大端的转换器),但它不是一个“完整的”解决方案。它只是“基础”仪器。而且我知道BinaryWriter/ BinaryReader,但是它们似乎不支持不支持的数组,byte[]或者char[]它们似乎无法在写入时“填充”数组(您有一个 5 元素byte[]数组,您需要编写它作为 10 个元素byte[]的数组,因为您使用的格式需要它...您必须编写代码行来执行此操作)

计划 B(甚至可能是计划 Z)是unsafe struct为每个类创建一个影子,一个IWysiwygSerializable具有两个方法(ReadWrite)的接口并在每个类中实现接口(写入将填充unsafe struct并写入输出流,读取将做相反的事情)(或者我什至可以BitConverter在不使用的情况下直接做几十个Read,但对于数组来说有点困难)Writestruct

谢谢!

4

3 回答 3

3

我为声明性二进制序列化编写了一个相当简单但可扩展的框架。我在工作中广泛使用了它,并且总是发现它可以节省大量的精力:

binaryserializer.com

于 2013-03-08T04:50:10.057 回答
2

不要使用 BinaryFormatter。而是使用 BinaryWriter 和 BinaryReader 以您想要的确切顺序将要写入磁盘的确切字节写入磁盘。如果数组没有按照您喜欢的方式处理,那么您只需要自己循环遍历数组。为了使它看起来更清晰,您也许可以编写一个扩展方法来执行循环。

于 2011-06-18T16:16:52.610 回答
0

(请注意,这可能被视为广告,但“产品”是开源的 MIT 许可,甚至其他引用的“产品”也是开源的 MIT 许可)(请注意,我是广告“产品”的作者和另一个引用的“产品”)

没有任何“好的”解决方案,所以我完成了我的 :-) 我必须创建一个库来创建库:FluentSerializer。该库可用于创建您希望如何序列化二进制数据的“描述”。这个描述是用流利的符号写的。您可以(通过我编写的另一个库FluentStatement)在您的流利描述中包含所有常见的语句,例如while, if, for... (即使有一个流利的符号也很明显)。然后将您的描述编译为表达式树,然后编译为一组动态方法(序列化、反序列化和大小(序列化数据))。

测试类的序列化程序的小样本

/// <summary>
/// 
/// </summary>
public class Serializer : ISerializer<MyClass, EmptyParameters>
{
    #region ISerializer<MyClass,EmptyParameters> Members

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public Expression<Serializer<MyClass, EmptyParameters>> GetSerializer()
    {
        return (op, obj, par) => Statement.Start(fl => fl
            .Serialize(obj.Version)

            // Static objects can be serialized/deserialized.
            .Serialize(MyClass.StaticReadonlyInts1, typeof(FixedLength<>))

            // So can readonly collections.
            .Serialize(obj.ReadonlyInts1, typeof(FixedLength<>))

            // Both array and List<> (and Dictionary<,>, and SortedDictionary<,>, and
            // many other types of collections)
            ////.Serialize(obj.ReadonlyList1)
            .Serialize(obj.ReadonlyList1, typeof(VariableLengthByte<>))

            ////// Readonly fields can be serialized/deserialized.
            ////// Sadly you can't Dump() serializers that replace read only fields
            ////// (replace is the keyword here, readonly int X is a no-no, 
            ////// readonly List<int> X is a yes, readonly int[] X is a yes if it's 
            ////// FixedLength<>.
            ////.Serialize(obj.ReadonlyInt1)

            .Serialize(obj.Bool1)
            .Serialize(obj.Int2)

            // This will be serialized/deserialized only if obj.Version != 0
            // It's only an example of what you can do. You can use the full power of
            // FluentStatement, and remember that if instead of EmptyParameters you
            // had used another class as the parameters, you could have manipulated it
            // through the par object, so par.Version for example.
            .If(obj.Version != 0, fl.Serialize(obj.Int3))

            // This if(s) depend on the operation that is being done
            // (serialization/deserialization/size)
            .If(op == Operation.Serialize, fl.Serialize(obj.Int2))
            .If(op == Operation.Deserialize, fl.Serialize(obj.Int3))

            .Serialize(obj.Short1)

            // Tuples are supported.
            .Serialize(obj.Tuple1)

            // Arrays need to have the length prepended. There are helpers for this.
            // The default helper can be specified in the Serializer<T> constructor and
            // will be used if the field serializer isn't specified.
            ////.Serialize(obj.Ints1)

            // Or you can specify it:
            .Serialize(obj.Ints2, typeof(VariableLengthByte<>))
            .Serialize(obj.Ints3, typeof(VariableLengthByte<int[]>))

            // Nullable types are supported
            .Serialize(obj.NullableInt1, typeof(Nullable<int>))
            ////.Serialize(obj.NullableInt2)

            // But note that you could even use the Optional<> with value types,
            // usefull for example if you have to use a modifier that is a class
            // (like VariableLengthInt32 for example)
            .Serialize(obj.NullableInt1, typeof(Optional<int>))
            .Serialize(obj.NullableInt2, typeof(Optional<>))

            // So are "optional" objects (fields that can be null)
            // (Note that here if we wanted to specify the helper, we would have
            // to use typeof(Optional<VariableLengthByte<int>>)
            .Serialize(obj.OptionalInts1, typeof(Optional<VariableLengthInt32<int[]>>))
            .Serialize(obj.OptionalInts2, typeof(Optional<>))
            .Serialize(obj.OptionalList1, typeof(Optional<VariableLengthInt32<List<int>>>))
            .Serialize(obj.OptionalList2, typeof(Optional<>))

            // You can serialize a DateTime as the full .NET value
            .Serialize(obj.DateTime1)

            // Or, for example, as an Unix datetime (32 or 64 bits)
            .Serialize(obj.DateTime2, typeof(UnixDateTime<int>))

            .Serialize(obj.Float1)
            .Serialize(obj.Double1)
            .Serialize(obj.Decimal1)
            .Serialize(obj.TimeSpan1)

            // For strings it's a little more complex. There are too many combinations 
            // of possible formats (encoding x string length * (use char or byte length))
            // At this time there isn't any helper for C strings (null terminated strings).
            // You have to "manually" register you string formats.
            .Serialize(obj.String1, typeof(Program.MyUtf8VariableLengthInt32String))
            .Serialize(obj.String2, typeof(Program.MyAsciiVariableLengthInt32String))
            .Serialize(obj.String3, typeof(Program.MyUnicodeVariableLengthInt32String))

            // Chain serializing the base class can be done in this way
            .Serialize(obj, typeof(MySimpleClass))

            // This is only to make it easy to add new serialization fields. The last ) is
            // "attached" to the .Empty and doesn't need to be moved.
            .Empty());
    }

    #endregion
}

显然,只有当您必须序列化/反序列化大量数据时,这个库才是好的。如果您只有一个对象要序列化/反序列化,BinaryReader/BinaryWriter对您来说可能就足够了(正如我在原始问题中和 Fantius 在他的回答中所建议的那样)。

于 2012-09-01T13:54:35.617 回答