NameValueCollection上的Keys和AllKeys属性有什么区别?
-
03-07-2019 - |
题
System.Collections.Specialized.NameObjectCollectionBase有两个类似的属性:
string[] AllKeys
NameObjectCollectionBase.KeyCollection Keys
他们提供不同的数据集吗?我什么时候想要使用另一个?
解决方案
AllKeys
是 O(n)
操作,而 Keys
是 O(1)
。这是因为 AllKeys
将密钥复制到一个新数组中,而 Keys
只返回对 NameValueCollection
的私钥集合的引用。因此,除了性能上的差异之外, Keys
返回的集合将随基本集合而变化,因为它只是对原始集合的引用,而 AllKeys
将与更改隔离,因为这是一份副本。
这个小测试程序显示了行为上的差异:
using System;
using System.Collections.Specialized;
static class Program
{
static void Main()
{
var collection = new NameValueCollection();
var keys = collection.Keys;
var allKeys = collection.AllKeys;
collection.Add("Name", "Value");
Console.WriteLine("Keys: " + keys.Count);
Console.WriteLine("AllKeys: " + allKeys.Length);
Console.ReadLine();
}
}
输出结果为:
Keys: 1
AllKeys: 0
不隶属于 StackOverflow