.NET 中的双向映射

发布于 2024-07-26 15:00:43 字数 197 浏览 5 评论 0原文

是否有可用于双向查找的 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轻许诺言 2024-08-02 15:00:43

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 for O(1) lookup in both directions.

紫竹語嫣☆ 2024-08-02 15:00:43

如果只有 10 个很少发生变化的情况,使用 Switch 语句的几种方法可能就足够了。

如果您可以控制静态对象,那么它们都可以实现一个返回“序列化代码”字符的新接口:

public interface IStaticObject
{
    char SerializationCode { get; };
}

因此,朝这个方向前进很容易:someObject.SerializationCode。 然后,您还可以让静态对象全部使用构造函数,该构造函数将其 SerializationCode 注册到具有字典的单例实例。

public class SomeStaticObject : IStaticObject
{
    public void SomeStaticObject()
    {
        StaticObjectRegistrar.Register(this.SerializationCode, this);
    }

    public char SerializationCode
    {
        get
        {
            return ?;
        }
    }
}

反序列化时,您只需获取该字符并通过该字典运行它即可获取静态对象。

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:

public interface IStaticObject
{
    char SerializationCode { get; };
}

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.

public class SomeStaticObject : IStaticObject
{
    public void SomeStaticObject()
    {
        StaticObjectRegistrar.Register(this.SerializationCode, this);
    }

    public char SerializationCode
    {
        get
        {
            return ?;
        }
    }
}

Deserializing, you just take the character and run it through that dictionary to get the static object back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文