0

有没有办法找出字典中引用的最后一个索引?例如,

Dictionary<string,string> exampleDic;

...

exampleDic["Temp"] = "ASDF"

...

有没有办法以某种方式检索“Temp”而不将其存储为变量?

4

3 回答 3

2

实现自己的字典

public class MyDic : Dictionary<String, String>
{
    public string LastKey { get; set; }

    public String this[String key]
    {
        get
        {
            LastKey = key;
            return this.First(x => x.Key == key).Value;
        }
        set
        {
            LastKey = key;
            base[key] = value; // if you use this[key] = value; it will enter an infinite loop and cause stackoverflow
        }
    }

然后在你的代码中

    MyDic dic = new MyDic();
    dic.Add("1", "one");
    dic.Add("2", "two");
    dic.Add("3", "three");

    dic["1"] = "1one";

    dic["2"] = dic.LastKey; // LastKey : "1"

    dic["3"] = dic.LastKey; // LastKey : "2";
于 2012-10-14T06:28:17.117 回答
0

不,没有任何东西可以存储这个(这是一个非常不寻常的要求),所以你必须自己做这个。

于 2012-10-14T06:10:38.807 回答
0

你为什么不去通用字典:

public class GenericDictionary<K, V> : Dictionary<K, V>
{
    public K Key { get; set; }

    public V this[K key]
    {
        get
        {
            Key = key;
            return this.First(x => x.Key.Equals(key)).Value;
        }
        set
        {
            Key = key;
            base[key] = value;
        }
    }
}

用法:

Dictionary<string, string> exampleDic;
...
exampleDic["Temp"] = "ASDF"
var key = exampleDic.Key;
于 2012-10-14T06:34:03.977 回答