【问题标题】:define two dimensional array in c# with string indexes在 C# 中使用字符串索引定义二维数组
【发布时间】:2014-12-24 11:04:40
【问题描述】:

如何在 c# 中定义这样的东西:

list["alpha","beta"] = value;

我想访问字典等值:

var item = list["alpha","beta"];

【问题讨论】:

  • .NET Framework 中没有这种类型。您需要实现自己的类型以满足您的需求。
  • 我觉得你应该定义一个Dictionary>,然后就可以作为dict[key1[key2]]访问了..有用吗?
  • 这个问题可能是重复的,但不是所选问题。这个问题要求的是多键字典,而不是多值字典。

标签: c# arrays list


【解决方案1】:

您需要的不是二维数组,而是字典。 请参阅字典文档here

然后您将编写 myDic[ "outerDicKey" ][ "innerDicKey" ] 来检索值。

【讨论】:

  • 另一种方法是从Dictionary<TKey, TValue> 继承并使用元组作为基本字典类的键,并添加必要的this[string key1, string key2] 和相应的添加、删除、包含键等,即。 public class DualKeyDictionary<TKey, TValue> : Dictionary<Tuple<TKey, TKey>, TValue> { ... }
  • 确实如此。警告:元组仅适用于 .NET 4。
【解决方案2】:

实现聚合字典的类型:

class Test
{
    private struct Key
    {
        public string Key1 { get; set; }

        public string Key2 { get; set; }

        public Key(string key1, string key2) 
            : this()
        {
            Key1 = key1;
            Key2 = key2;
        }
    }

    private readonly Dictionary<Key, object> _dictionary = new Dictionary<Key, object>();

    public object this[string key1, string key2]
    {
        get { return _dictionary[new Key(key1, key2)]; }
        set { _dictionary[new Key(key1, key2)] = value; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多