本文介绍了双向在C#/双向词典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要存储在下列方式在字典中的字:

I want to store words in a dictionary in following way:

我能获得这个词code。通过字:字典[SomeWord]​​ - > 123 和得到一个字一个字code:词典[123] - > SomeWord

I can get word code by word: dict["SomeWord"] -> 123 and get word by word code: dict[123] -> "SomeWord"

是真的吗?当然,要做到这一点的一种方法是两本词典:词典<字符串,INT> 词典< INT,字符串> 但有另一种方式?

Is it real? Of course one way to do it is two dictionaries: Dictionary<string,int> and Dictionary<int,string> but is there another way?

推荐答案

我写了一个快速几个类,让你做你想做的。你可能会需要用更多的功能扩展,但它是一个很好的起点。

I wrote a quick couple of classes that lets you do what you want. You'd probably need to extend it with more features, but it is a good starting point.

使用的code是这样的:

The use of the code looks like this:

var map = new Map<int, string>();

map.Add(42, "Hello");

Console.WriteLine(map.Forward[42]);
// Outputs "Hello"

Console.WriteLine(map.Reverse["Hello"]);
//Outputs 42

下面的定义:

public class Map<T1, T2>
{
    private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
    private Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();

    public Map()
    {
        this.Forward = new Indexer<T1, T2>(_forward);
        this.Reverse = new Indexer<T2, T1>(_reverse);
    }

    public class Indexer<T3, T4>
    {
        private Dictionary<T3, T4> _dictionary;
        public Indexer(Dictionary<T3, T4> dictionary)
        {
            _dictionary = dictionary;
        }
        public T4 this[T3 index]
        {
            get { return _dictionary[index]; }
            set { _dictionary[index] = value; }
        }
    }

    public void Add(T1 t1, T2 t2)
    {
        _forward.Add(t1, t2);
        _reverse.Add(t2, t1);
    }

    public Indexer<T1, T2> Forward { get; private set; }
    public Indexer<T2, T1> Reverse { get; private set; }
}

这篇关于双向在C#/双向词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:24