命名空间: System.Linq
程序集: System.Core(在 System.Core.dll 中)
此方法通过使用延迟执行实现。即时返回值为一个对象,该对象存储执行操作所需的所有信息。只有通过直接调用对象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)来枚举该对象时,才执行此方法表示的查询。
OfType<(Of <(TResult>)>)(IEnumerable) 方法仅返回 source 中那些可以转换为 TResult 类型的元素。如果元素不能转换为 TResult 类型,但却不想接收异常,则使用 Cast<(Of <(TResult>)>)(IEnumerable)。
此方法是少数标准查询运算符方法之一,标准查询运算符方法可应用于含有非参数化类型(如 ArrayList)的集合。这是因为 OfType<(Of <(TResult>)>) 扩展了类型 IEnumerable。OfType<(Of <(TResult>)>) 不仅无法应用于基于参数化的 IEnumerable<(Of <(T>)>) 类型的集合,也无法应用于基于非参数化的 IEnumerable 类型的集合。
通过将 OfType<(Of <(TResult>)>) 应用于实现 IEnumerable 的集合,可以获得使用标准查询运算符查询集合的能力。例如,将 Object 的类型参数指定为 OfType<(Of <(TResult>)>) 将返回一个对象,其类型为 C# 中的 IEnumerable<Object> 或 IEnumerable(Of Object) 中的 Visual Basic,标准查询运算符可应用于该对象。
C#代码:

Code
System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
fruits.Add("Mango");
fruits.Add("Orange");
fruits.Add("Apple");
fruits.Add(3.0);
fruits.Add("Banana");
// Apply OfType() to the ArrayList.
IEnumerable<string> query1 = fruits.OfType<string>();
Console.WriteLine("Elements of type 'string' are:");
foreach (string fruit in query1)
{
Console.WriteLine(fruit);
}
// The following query shows that the standard query operators such as
// Where() can be applied to the ArrayList type after calling OfType().
IEnumerable<string> query2 =
fruits.OfType<string>().Where(fruit => fruit.ToLower().Contains("n"));
Console.WriteLine("\nThe following strings contain 'n':");
foreach (string fruit in query2)
{
Console.WriteLine(fruit);
}
// This code produces the following output:
//
// Elements of type 'string' are:
// Mango
// Orange
// Apple
// Banana
//
// The following strings contain 'n':
// Mango
// Orange
// Banana