在KeyedCollection类型中加字典的TryGetValue方法(转)
.NET(C#):在KeyedCollection类型中加字典的TryGetValue方法
作者:_Mgen 来源:博客园 发布时间:2012-01-07 18:31 阅读:176 次 原文链接 [收藏]
TryGetValue方法很常用,可以把“判断键存在”和“根据键取值”两步转化为一步,这样键的哈希值只计算一次,是很有效率的。但注意IDictionary接口并没有定义TryGetValue,而泛型接口IDictionary<T, V>定义了TryGetValue。而KeyedCollection类型却继承自类型Collection<T>,Collection<T>继承接口ICollection<T>。原因应该是KeyedCollection不仅仅是字典,还包含一个线性表吧。因此KeyedCollection默认是没有TryGetValue的。
但是KeyedCollection有一个受保护成员:Dictionary属性。正好返回一个泛型的IDictionary代表内部字典,因此改写KeyedCollection时调用这个内部IDictionary的TryGetValue就可以了。
比如先定义一个简单的类型:Student,Id属性是成员的键。
class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
KeyedCollection这样定义:
//+ using System.Collections.ObjectModel;
class MyKeyedCollection : KeyedCollection<int, Student>
{
//辅助添加方法
public void Add(int id, string name)
{
Add(new Student() { Id = id, Name = name });
}
//改写抽象方法:GetKeyForItem
protected override int GetKeyForItem(Student item)
{
return item.Id;
}
//将受保护IDictionary的TryGetValue显式定义
public bool TryGetValue(int key, out Student value)
{
return Dictionary.TryGetValue(key, out value);
}
}
示例代码:
var dic = new MyKeyedCollection();
dic.Add(3, "martin");
dic.Add(1, "tony");
dic.Add(2, "liu");
Student st;
if (dic.TryGetValue(1, out st))
Console.WriteLine(st.Name);
else
Console.WriteLine("没找到");
输出:
tony
浙公网安备 33010602011771号