Is there a way cast an object back to it original type without specifing every case?

前端 未结 6 1379
眼角桃花
眼角桃花 2021-01-15 14:28

I have an array of different type objects and I use a BinaryWriter to convert each item to its binary equivalent so I can send the structure over the network.

I curr

6条回答
  •  不思量自难忘°
    2021-01-15 15:19

    Have you considered using a BinaryFormatter instead of the BinaryWriter?

    Advantages

    • You can pass objects (i.e. anything), so it solves your casting problem.
    • Automatic type management (actually writes type headers to the stream).
    • Supports complex reference types as well.

    Disadvantages

    Uses Serialization internally, therefore:

    • Probably slower.
    • Byte stream gets larger (because of the type headers).
    • You don't have control over the byte format, therefore not an option in interop scenarios.
    • Potential version issues (compatibility between different assembly versions of the serialized type).
    • Requires the serialization code access permission (relevant in partial trust scenarios).

提交回复
热议问题