English 中文(简体)
KeyValuePair与NameValueCollection
原标题:KeyValuePair vs. NameValueCollection

还有其他问题,比如KeyValuePair与IDictionary,但我觉得这一个略有不同。

<code>NameValueCollection</code>接受字符串键和字符串值。

KeyValuePair就像一本字典,你可以告诉它键和值的类型。

我不明白为什么存在NameValueCollection。用字符串类型初始化KeyValuePair似乎就足够了。我还注意到NameValueCollection还有一些方法可供使用,但为什么不将两个类合并为一个呢?

最佳回答

KeyValuePair不像字典。它只是一个包含键和值的元组。

NameValueCollection相当于IList<;KeyValuePair<;字符串,IList<;字符串>>>(请注意,NameValueCollection早于泛型)-像Get(string)这样的操作是O(n)或多个值(这与Dictionary<;string,string>;不同)。

原因在NameValueCollection文档

此类可用于标题、查询字符串和表单数据。

较新的“替换”数据结构是查找<;字符串,字符串>;。(但是,它不直接支持与spender注释一样不可变的操作。)

快乐的编码。

问题回答

NameValueCollection存在于.NET 1.0和1.1中,KeyValuePair是一种泛型类型,直到2.0才添加到.NET中。System.Collections.Specialized所有这些都早于泛型的添加;它包含某些强类型(如果愿意的话,可以专门化),以供用户在不必从对象转换到字符串的情况下使用。

KeyValuePair是用于迭代词典

var dictionary = new Dictionary<int,long>

foreach(var kvp in dictionary)
{
    // kvp is KeyValuePair<int,long>. kvp.Key is the int key and kvp.Value is the long value for the key
}

NameValueCollection是可索引的。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...