ObjectResult<T>.GetEnumerator 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回循环访问查询结果的枚举器。
public:
virtual System::Collections::Generic::IEnumerator<T> ^ GetEnumerator();
public System.Collections.Generic.IEnumerator<T> GetEnumerator();
abstract member GetEnumerator : unit -> System.Collections.Generic.IEnumerator<'T>
override this.GetEnumerator : unit -> System.Collections.Generic.IEnumerator<'T>
Public Function GetEnumerator () As IEnumerator(Of T)
返回
循环访问查询结果的枚举器。
实现
示例
此示例从Execute方法返回一个ObjectResult<T>。 然后,它会获取枚举器并循环访问查询结果。 最后,它会释放枚举器和 ObjectResult<T> 对象。
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
ObjectSet<Product> query = context.Products;
ObjectResult<Product> queryResults = null;
System.Collections.IEnumerator enumerator = null;
try
{
queryResults = query.Execute(MergeOption.AppendOnly);
// Get the enumerator.
enumerator = ((System.Collections.IEnumerable)queryResults).GetEnumerator();
// Iterate through the query results.
while (enumerator.MoveNext())
{
Product product = (Product)enumerator.Current;
Console.WriteLine("{0}", product.Name);
}
// Dispose the enumerator
((IDisposable)enumerator).Dispose();
}
finally
{
// Dispose the query results and the enumerator.
if (queryResults != null)
{
queryResults.Dispose();
}
if (enumerator != null)
{
((IDisposable)enumerator).Dispose();
}
}
}
注解
如果不再需要枚举器,则必须释放枚举器。 使用 foreach 语句(Visual Basic中的 For Each)可确保在结果迭代完成时正确释放枚举器。