.NET 中的双向映射
是否有可用于双向查找的 .NET 数据结构?
问题在于:序列化。 我的对象包含一个指向 10 个预定义静态对象之一的字段。 写入文件时,我写入一个字符来表示正在引用 10 个对象中的哪一个。 此时,我需要一个查找数据结构,它允许我根据所引用的对象获取字符代码。 反序列化时,我需要做相反的事情。 我能想到很多其他可以使用这种数据结构的地方。
Is there a .NET data structure I could use for bidirectional lookup?
Here's the problem: Serialization. My object contains a field which points to one of 10 predefined static objects. When writing to the file, I write a single character representing which of the 10 objects is being referenced. At this point, I need a lookup datastructure which will allow me to get the character code based on the object being referenced. When deserializing, I need to do the reverse. I can think of a lot of other places where I could use such a data structure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将创建一个包含两个通用
字典
< 的数据结构/a> 相互镜像的对象,其中一个的键代表另一个的值,反之亦然。 这将允许双向O(1)
查找。I would create a data structure that contains two generic
Dictionary
objects that mirror each other in such a way that the key of one represents the value of the other and vice versa. This would allow forO(1)
lookup in both directions.如果只有 10 个很少发生变化的情况,使用 Switch 语句的几种方法可能就足够了。
如果您可以控制静态对象,那么它们都可以实现一个返回“序列化代码”字符的新接口:
因此,朝这个方向前进很容易:someObject.SerializationCode。 然后,您还可以让静态对象全部使用构造函数,该构造函数将其 SerializationCode 注册到具有字典的单例实例。
反序列化时,您只需获取该字符并通过该字典运行它即可获取静态对象。
In the case of only 10 cases that will rarely change, a couple of methods using Switch statements would probably suffice.
If you have control of the static objects, then they could all implement a new interface that returns a "serialization code" character:
Therefore, going in that direction is easy: someObject.SerializationCode. Then you could also have your static objects all use a constructor that registers their SerializationCode with a singleton instance that has a Dictionary.
Deserializing, you just take the character and run it through that dictionary to get the static object back.