在 C# .NET 中,是否有 StringDictionary 没有复制构造函数的原因?
如果这是一个愚蠢的问题,我深表歉意,但请听我说:
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);
在上面的代码示例中,我可以创建通用字典的副本。
现在假设我正在使用 System.Collections.Specialized.StringDictionary,因为我不想在任何地方键入“字符串”类型。 StringDictionary 没有复制构造函数! 事实上,它只有默认的构造函数。
当然,我可以迭代 StringDictionary 并手动添加每个键/值对,但我不想:-P
为什么没有复制构造函数? 我在这里错过了什么吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
StringDictionary
类型已经过时了。 我认为Dictionary
就是您想要在此处使用的内容。Dictionary
类型实现了一些强类型接口(ICollection>
和IEnumerable ;>
),这使得它比StringDictionary
类型更有用。虽然
StringDictionary
类型是强类型的,但我不会仅仅因为懒惰而建议使用它。The
StringDictionary
type is rather obsolete. I think thatDictionary<String,String>
is what you want to use here.The
Dictionary<TKey,TValue>
type implements some strongly-typed interfaces (ICollection<KeyValuePair<TKey, TValue>>
andIEnumerable<KeyValuePair<TKey, TValue>>
) which makes it more useful than theStringDictionary
type.While the
StringDictionary
type is strongly typed I wouldn't advise its use for the sake of laziness alone.如果您确实想使用 StringDictionary(也许是为了支持旧版应用程序),您可以创建一个扩展方法:
然后您可以执行以下操作:
If you really want to use a StringDictionary (perhaps to support a legacy application), you can create an extension method:
Then you can do this:
我同意共识 - 你最好使用
Dictionary
。 但如果您不喜欢一直输入泛型类型,您可以创建自己的子类:Et Voila! 每当您想使用字符串
Dictionary
时,您可以使用StringDict
相反。I agree with the consensus -- you're better off using
Dictionary<string, string>
. But if you don't like typing the generic types all the time, you could create your own subclass:Et Voila! Whenever you want to use a string
Dictionary
, you useStringDict
instead.如果您不想在任何地方键入“字符串”类型,但又对
Dictionary
感到满意,则创建一个新类,该类是Dictionary< /code> 并且不要覆盖任何方法。 您甚至可以将其称为
StringDictionary
,只要它位于不同的命名空间中即可。If you don't want to type the "string" types anywhere but are otherwise happy with
Dictionary<string,string>
, then create a new class that subclassesDictionary<string,string>
and just don't override any methods. You can even call itStringDictionary
, as long as it's in a different namespace.