代码之家  ›  专栏  ›  技术社区  ›  Pandincus

在C#中。NET,StringDictionary没有复制构造函数有什么原因吗?

  •  2
  • Pandincus  · 技术社区  · 17 年前

    Dictionary<string, string> genericDict = new Dictionary<string, string>;
    genericDict.Add("blah", "bloop");
    // Use the copy constructor to create a copy of this dictionary
    return new Dictionary<string, string>(genericDict);
    

    现在假设我正在使用一个系统。收藏。专业的。StringDictionary,因为我不想在任何地方都键入“string”类型。StringDictionary没有复制构造函数!事实上,它只有默认构造函数。

    4 回复  |  直到 17 年前
        1
  •  9
  •   Andrew Hare    17 年前

    这 StringDictionary 这种类型已经相当过时了。我认为 Dictionary<String,String> 这就是你想在这里使用的。

    这 Dictionary<TKey,TValue> ICollection<KeyValuePair<TKey, TValue>> 和 IEnumerable<KeyValuePair<TKey, TValue>> )这使得它比 字符串字典 类型。

    而 字符串字典 类型 是 我不会仅仅因为懒惰而建议使用它。

        2
  •  5
  •   Keltex    17 年前

    如果你真的想使用StringDictionary(也许是为了支持 遗留应用程序 ),您可以创建一个扩展方法:

    public static StringDictionary NewCopy(this StringDictionary olddict)
    {
        var newdict = new StringDictionary();
        foreach (string key in olddict.Keys)
        {
            newdict.Add(key, olddict[key]);
        }
        return newdict;
    }
    

    StringDictionary newdict = olddict.NewCopy();
    
        3
  •  2
  •   Randolpho    17 年前

    我同意这个共识——你最好使用 Dictionary<string, string> 。但如果你不喜欢一直键入泛型类型,你可以创建自己的子类:

    public class StringDict : Dictionary<string, string>
    {
      // duplicate all Dictionary's constructors here, calling the base constructor for each. 
    }
    

    瞧! 每当你想使用字符串时 Dictionary ,你使用 StringDict 相反。

        4
  •  1
  •   Tadmas    17 年前

    如果你不想在任何地方键入“string”类型,但对其他方面感到满意 Dictionary<string,string> ,然后创建一个子类 不要覆盖任何方法。你甚至可以称之为 StringDictionary ,只要它位于不同的命名空间中。

    推荐文章