Aracılığıyla paylaş


Nasıl yapılır: sorgu ifadelerde (C# Programlama Kılavuzu) özel durumları işlemek

Bir sorgu ifadesinde içeriğinde herhangi bir yöntemi çağırmak mümkündür.Bununla birlikte, veri kaynağı içeriğini değiştirme veya bir özel durum üretiliyor gibi bir yan etkisi oluşturabilirsiniz bir sorgu ifadesinde herhangi bir yöntemini çağırmadan kaçının öneririz.Bu örnek genel ihlal bir sorgu ifadesinde yöntemlerini çağırdığınızda özel durumları yükseltme önlemek gösterilmiştir .NET Framework özel durum işleme yönergeleri.Neden bu verilen içerikte atılan alınamadığını belirli bir özel durumu yakalamak için kabul edilebilir olan bu yönergeleri durumu.Daha fazla bilgi için bkz. Özel durumları için en iyi yöntemler.

Son örnek, bir sorgu yürütme sırasında bir özel durum gerekir, bu gibi durumlarda işlemek gösterilmiştir.

Örnek

Aşağıdaki örnek, özel durum kodu dışında bir sorgu ifadesinde taşınması gösterilmiştir.Bu, ayrıca yöntemi üzerinde herhangi bir sorgu yerel değişkenleri bağlı değildir, yalnızca mümkündür.

class ExceptionsOutsideQuery
{
    static void Main()
    {
        // DO THIS with a datasource that might
        // throw an exception. It is easier to deal with
        // outside of the query expression.
        IEnumerable<int> dataSource;
        try
        {
            dataSource = GetData();
        }
        catch (InvalidOperationException)
        {
            // Handle (or don't handle) the exception 
            // in the way that is appropriate for your application.
            Console.WriteLine("Invalid operation");
            goto Exit;
        }

        // If we get here, it is safe to proceed.
        var query = from i in dataSource
                    select i * i;

        foreach (var i in query)
            Console.WriteLine(i.ToString());

        //Keep the console window open in debug mode
        Exit:
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // A data source that is very likely to throw an exception!
    static IEnumerable<int> GetData()
    {
        throw new InvalidOperationException();
    }
}

Bazı durumlarda, sorgu yürütme hemen durdurmak için bir sorgu içinde atılan bir özel durum için en iyi yanıtı olabilir.Aşağıdaki örnek, gelen bir sorgu gövdesi içinde atılan özel durumlarý iþlemek gösterilmiştir.İstediğinizi düşünelim SomeMethodThatMightThrow durdurmak için sorgu yürütme gerektiren bir özel duruma neden olabilir.

Dikkat try blok kapsayan foreach döngü ve sorgu kendisi.Bu, çünkü foreach döngü noktasıdır, sorgu aslında gerçekleştirilir.Daha fazla bilgi için bkz. Giriş LINQ sorguları (C#).

class QueryThatThrows
{
    static void Main()
    {
        // Data source.
        string[] files = { "fileA.txt", "fileB.txt", "fileC.txt" };

        // Demonstration query that throws.
        var exceptionDemoQuery =
            from file in files
            let n = SomeMethodThatMightThrow(file)
            select n;

        // Runtime exceptions are thrown when query is executed.
        // Therefore they must be handled in the foreach loop.
        try
        {
            foreach (var item in exceptionDemoQuery)
            {
                Console.WriteLine("Processing {0}", item);
            }
        }

        // Catch whatever exception you expect to raise
        // and/or do any necessary cleanup in a finally block
        catch (InvalidOperationException e)
        {
            Console.WriteLine(e.Message);
        }

        //Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Not very useful as a general purpose method.
    static string SomeMethodThatMightThrow(string s)
    {
        if (s[4] == 'C')
            throw new InvalidOperationException();
        return @"C:\newFolder\" + s;
    }
}
/* Output:
    Processing C:\newFolder\fileA.txt
    Processing C:\newFolder\fileB.txt
    Operation is not valid due to the current state of the object.
 */

Kod Derleniyor

  • Oluşturma bir Visual Studio hedefleyen bir proje.net Framework sürüm 3.5.Varsayılan olarak, proje başvuru System.Core.dll sahiptir ve bir using System.Linq ad alanı için yönerge.

  • Projenize kodu kopyalayın.

  • Derlemek ve program çalıştırmak için F5 tuşuna basın.

Konsol penceresine çıkmak için herhangi bir tuşa basın.

Ayrıca bkz.

Kavramlar

LINQ sorgu ifadelerini (C# Programlama Kılavuzu)