如何确保 T 可以固定字节数进行序列化?
我正在编写一个保留在磁盘上的通用 DataStructure
,并且我需要编写它,以便保证 T
能够以固定字节数进行序列化。例如,应接受 int
和 char
,但不应接受 string
或 int[]
。同样,具有 string
成员的 struct
是不可接受的,但具有 fixed char
数组的 unsafe struct
是可接受的。
我可以使用反射和 sizeof 在初始化程序中编写运行时测试来测试每个成员,但这似乎是一个可怕的黑客行为。有没有有效且(相对)安全的方法来做到这一点?
I'm writing a generic DataStructure<T>
which persists on the disk, and I need to write it such that T
is guaranteed to be serializable in a fixed number of bytes. For example, int
and char
should be accepted, but string
or int[]
should not be. Likewise, a struct
with a string
member is not acceptable, but an unsafe struct
with a fixed char
array is.
I could write a runtime test in the initializer using reflection and sizeof
to test each member, but that seems like a terrible hack. Is there any efficient and (relatively) safe way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有办法静态支持仅具有固定特定大小的通用参数。约束仅限于接口、引用/结构、基类和
new
。不过,您可以做的是使用静态工厂方法将泛型的使用限制为合适的已知有限类型集。例如,
这有限制,因为它要求您提前列出所有可比较的类型。如果您想要一个更灵活的解决方案来处理用户定义的类型,您将需要实现运行时检查。
There is no way to statically support a generic parameter which only have a fixed specific size. Constraints are limited to interfaces, ref / struct, base class and
new
.What you can do though is use static factory methods to limit the uses of the generic to a known finite set of types which are suitable. For example
This is limiting though because it requires you to list all comparable types ahead of time. If you want a more flexible solution that works with user defined types you'll need to implement a runtime check.
每个直接或间接仅包含值类型但不包含引用类型的值类型都有大小限制。测试它的唯一方法是在运行时使用反射。
如果这是一个好主意,那就是另一个问题了,我想说这不是一个好主意。在我看来,序列化类型的原始数据通常是一个坏主意。
Every valuetype that directly or indirectly contains only value types, but no reference types has a limited size. The only way to test that is at runtime using reflection.
If that is a good idea is a different question, and I'd say it's not a good idea. Serializing the raw data of a type is generally a bad idea IMO.