中国开发网: 论坛: .NET/C#: 贴子 652817
龙之吻
在.net3.5下重写了坛子某位大虾的代码。
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MyCollection
{
public class ExtendCollection<T> : Collection<T> where T : class
{
/// <summary>
/// 从Collection取得类型为K的所有类型,K为T的子类。
/// </summary>
/// <typeparam name="K">K为待取类型</typeparam>
/// <returns>返回所有类型为K的枚举器</returns>
public IEnumerable<K> GetEnumerator<K>() where K : class, T
{
foreach (T t in base.Items)
{
if (t is K) yield return t as K;
}

}

/// <summary>
/// 从Collection取得类型为K的所有类型,K为T的子类。
/// </summary>
/// <typeparam name="K">K为待取类型</typeparam>
/// <returns>返回所有类型为K的集合</returns>
public ICollection<K> GetItems<K>() where K : class, T
{
ICollection<K> c = new Collection<K>();
foreach (T t in base.Items)
{
if (t is K) c.Add(t as K);
}
return c;
}

/// <summary>
/// 从Collection中取得第一个类型为K的实例
/// </summary>
/// <typeparam name="K">K为待取类型</typeparam>
/// <returns>类型为K的实例</returns>
public K First<K>() where K : class, T
{
foreach (T t in base.Items)
{
if (t is K) return t as K;
}
return null;

}
}
}



using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;


namespace MyCollection
{
/// <summary>
/// 扩展集合类,使用了LinQ对ExtendCollection<T>在.net3.5下进行了重写
/// </summary>
/// <typeparam name="T">类型参数T</typeparam>
public class MyExtendCollection<T> : Collection<T> where T : class
{
/// <summary>
/// 从Collection取得类型为K的所有类型,K为T的子类。
/// </summary>
/// <typeparam name="K">K为待取类型</typeparam>
/// <returns>返回所有类型为K的枚举器</returns>
public IEnumerable<K> GetEnumerator<K>() where K : class, T
{
return base.Items.Where(t => t is K).Select(t => t as K);
}

/// <summary>
/// 从Collection取得类型为K的所有类型,K为T的子类。
/// </summary>
/// <typeparam name="K">K为待取类型</typeparam>
/// <returns>返回所有类型为K的集合</returns>
public ICollection<K> GetItems<K>() where K : class, T
{
return base.Items.Where(t => t is K).Select(t => t as K).ToList();
}

/// <summary>
/// 从Collection中取得第一个类型为K的实例
/// </summary>
/// <typeparam name="K">K为待取类型</typeparam>
/// <returns>类型为K的实例</returns>
public K First<K>() where K : class, T
{
return (base.Items.Where(t => t is K).First() as K);
}

}
}


机器人,这首歌学会了没有?

我们的目标是->没有蛀牙!

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录