linq-Cast
源码:
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) { IEnumerable<TResult> typedSource = source as IEnumerable<TResult>; if (typedSource != null) return typedSource; if (source == null) throw Error.ArgumentNull("source"); return CastIterator<TResult>(source); } static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) { foreach (object obj in source) yield return (TResult)obj; }
看到yield,这是一个转换成延时加载的Enumerable,return (TResult)obj;具体实现用的是强制类型转换。
,使用
// Custom class.
class Clump<T> : List<T>
{
// Custom implementation of Where().
public IEnumerable<T> Where(Func<T, bool> predicate)
{
Console.WriteLine("In Clump's implementation of Where().");
return Enumerable.Where(this, predicate);
}
}
Clump<string> fruitClump = new Clump<string> { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; //var t1 = fruitClump.Where(f => f.Contains("o")); //var t2 = fruitClump.AsQueryable().Where(f => f.Contains("o")); //var t3 = fruitClump.AsEnumerable().Where(f => f.Contains("o")); for (int i = 0; i < fruitClump.Cast<string>().Count(); i++) { Console.WriteLine(fruitClump.Cast<string>().ToList()[i]); }