Aracılığıyla paylaş


when (C# başvurusu)

Aşağıdaki bağlamlarda bir filtre koşulu belirtmek için bağlamsal anahtar sözcüğünü kullanırsınız when :

when catch yan tümcesinde

Anahtar when sözcüğü, belirli bir özel durumun yürütülmesi için işleyici için true olması gereken bir koşul belirtmek üzere catch yan tümcesinde kullanılabilir. Söz dizimi şöyledir:

catch (ExceptionType [e]) when (expr)

burada ifade , Boole değeri olarak değerlendirilen bir ifadedir. döndürürse true, özel durum işleyicisi yürütülür; ise falseyürütülmüyor.

Aşağıdaki örnek, özel durum iletisinin when metnine bağlı olarak bir HttpRequestException için işleyicileri koşullu olarak yürütmek için anahtar sözcüğünü kullanır.

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Console.WriteLine(MakeRequest().Result);
    }

    public static async Task<string> MakeRequest()
    {
        var client = new HttpClient();
        var streamTask = client.GetStringAsync("https://localHost:10000");
        try
        {
            var responseText = await streamTask;
            return responseText;
        }
        catch (HttpRequestException e) when (e.Message.Contains("301"))
        {
            return "Site Moved";
        }
        catch (HttpRequestException e) when (e.Message.Contains("404"))
        {
            return "Page Not Found";
        }
        catch (HttpRequestException e)
        {
            return e.Message;
        }
    }
}

Ayrıca bkz.