有没有办法找出字典中引用的最后一个索引?例如,
Dictionary<string,string> exampleDic;
...
exampleDic["Temp"] = "ASDF"
...
有没有办法以某种方式检索“Temp”而不将其存储为变量?
答案 0 :(得分: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";
答案 1 :(得分:0)
没有。什么都没有存储(这是一个非常不寻常的要求),所以你必须自己做。
答案 2 :(得分: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;