ObjectResult<T>.GetEnumerator 方法

定義

傳回逐一查看查詢結果的列舉值。

C#
public System.Collections.Generic.IEnumerator<T> GetEnumerator();

傳回

逐一查看查詢結果的列舉值。

實作

範例

這個範例會 ObjectResult<T> 從 方法傳 Execute 回 。 然後,它會取得列舉值並且逐一查看查詢結果。 最後,它會釋放列舉值和 ObjectResult<T> 物件。

C#
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();
        }
    }
}

備註

不再需要此列舉值時,就會加以處置 (Dispose)。 foreach在 Visual Basic 中使用 語句 (For Each) 可確保在結果的反覆專案完成時,會正確處置列舉值。

適用於

產品 版本
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

另請參閱