AsEnumerable()
可以返回IEnumerable
类型。
下面的例子中我们创建一个SpecialList类继承自List,然后自定义Any()
方法隐藏掉List中的Any()
方法。(List中的Any()
方法在List不为空的时候直接调用不传入条件会返回true
,空时返回false
)
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public static class Program
{
private class SpecialList<T> : List<T>
{
public bool Any()
{
return false;
}
}
static void Main( string[] args )
{
SpecialList<int> numbers = new SpecialList<int>() { 1, 2, 3 };
bool isAny = numbers.Any();
bool isAnyLinq = numbers.AsEnumerable().Any();
System.Console.WriteLine( "numbers:{0}", numbers.Text() );
System.Console.WriteLine( "any :{0}", isAny );
System.Console.WriteLine( "anyLINQ:{0}", isAnyLinq );
System.Console.ReadKey();
}
public static string Text( this IEnumerable i_source )
{
string text = string.Empty;
foreach( var value in i_source )
{
text += string.Format( "[{0}], ", value );
}
return text;
}
}
numbers:[1], [2], [3],
any :False
anyLINQ:True