如何在c#中给字典赋予运行时名称
本文关键字:运行时 字典 | 更新日期: 2023-09-27 18:17:45
我正在制作c#应用程序。在该应用程序中,我想在运行时创建字典。在这里,我从不同的端口获得数据,如1000、2000、3000等。这里我想创建字典运行时的名称为Dictionary1000, Dictionary2000, Dictionary3000等。但是我做不到。请帮帮我。提前感谢。
永远不要为索引使用变量名。使用字典中的字典
这种方法不太实用。为什么不用字典的字典呢?比如:
Dictionary<int, Dictionary<SomeType,SomeOtherType>>
这样就可以针对每个端口存储一个字典
public class NamedDictionary<TKey,TValue> : Dictionary<TKey,TValue> {
public string Name {get;set;}
}
……?
您也可以通过创建一个包含复合键的新类型来解决这个问题。
public class PortDictionary
{
private Dictionary<CompositeKey, MyValueType> _store = new Dictionary<CompositeKey, MyValueType>();
public void Add(int port, MyKeyType key, MyValueType value)
{
_store.Add(new CompositeKey(port, key), value);
}
public void Remove(int port, MyKeyType key)
{
_store.Remove(new CompositeKey(port, key));
}
public bool TryGet(int port, MyKeyType key, out MyValueType value)
{
return _store.TryGetValue(new CompositeKey(port, key), out value);
}
private class CompositeKey : IEquatable<CompositeKey>
{
private int _port;
private MyKeyType _key;
public CompositeKey(int port, MyKeyType key)
{
_port = port;
_key = key;
}
#region IEquatable<IdentityKey> Members
public bool Equals(CompositeKey other)
{
if (_port != other._port) {
return false;
}
return _key == other._key;
}
#endregion
public override int GetHashCode()
{
return _port.GetHashCode() ^ _key.GetHashCode();
}
}
}
在这个实现中,组合键是一个隐藏在端口字典中的本地类。复合键必须实现IEquatable<>并且必须重写GetHashCode()以便能够将其用作字典中的键。
下面是一个如何使用端口字典的示例:
var dict = new PortDictionary();
dict.Add(3000, myKey, myValue);
//Retrieve
if (dict.TryGet(3000, myKey, out myValue)) {
Console.WriteLine("Value = {0}", myValue);
} else {
Console.WriteLine("No value found for port {0} and key {1}", 3000, myKey);
}
使事情变得简单的技巧是重写[]:
public class InnerDictionary : Dictionary<int, string>
{
}
public class OuterDictionary : Dictionary<int, InnerDictionary>
{
public new InnerDictionary this[int key]
{
get
{
if (!base.ContainsKey(key))
{
base.Add(key, new InnerDictionary());
}
return base[key];
}
set { throw new NotSupportedException("Message"); }
}
}