"Property pattern"lar haqida...

nuriddin321

Nuriddin

Posted on May 30, 2022

"Property pattern"lar haqida...

C# 8 dan boshlab ifodani property yoki fieldarini 'property pattern' orqali solishtirish mumkin bo'ldi:

static bool IsConferenceDay(DateTime date) => date is { Year: 2020, Month: 5, Day: 19 or 20 or 21 };
Enter fullscreen mode Exit fullscreen mode

Property pattern - ifoda natijasi null bo'lmaganda ifodaga mos keladi va har bir ichki o'rnatilgan pattern ifoda natijasining tegishli xususiyati yoki maydoniga mos keladi.

Console.WriteLine(TakeFive("Hello, world!"));  // output: Hello
Console.WriteLine(TakeFive("Hi!"));  // output: Hi!
Console.WriteLine(TakeFive(new[] { '1', '2', '3', '4', '5', '6', '7' }));  // output: 12345
Console.WriteLine(TakeFive(new[] { 'a', 'b', 'c' }));  // output: abc

static string TakeFive(object input) => input switch
{
    string { Length: >= 5 } s => s.Substring(0, 5),
    string s => s,

    ICollection<char> { Count: >= 5 } symbols => new string(symbols.Take(5).ToArray()),
    ICollection<char> symbols => new string(symbols.ToArray()),

    null => throw new ArgumentNullException(nameof(input)),
    _ => throw new ArgumentException("Not supported input type."),
};
Enter fullscreen mode Exit fullscreen mode

Property pattern - rekursiv patterndir. Ya'ni, har qanday patternni ichki pattern sifatida ishlatishingiz mumkin. Quyidagi misolda ko'rsatilganidek, ma'lumotlar qismlarini ichki o'rnatilgan patternlarga moslashtirish uchun property patterndan foydalanilgan:

public record Point(int X, int Y);
public record Segment(Point Start, Point End);

static bool IsAnyEndOnXAxis(Segment segment) =>
    segment is { Start: { Y: 0 } } or { End: { Y: 0 } };
Enter fullscreen mode Exit fullscreen mode

Yuqoridagi misolda C# 9.0 va undan keyingi versiyalarida mavjud bo'lgan ikkita xususiyatdan foydalaniladi: or pattern combinator va record types.

C# 10 dan boshlab, siz ichki xususiyatlar yoki maydonlarga to'gridan-to'g'ri murojaat qilishingiz mumkin. Masalan, oldingi misoldagi usulni quyidagi ekvivalent kodga qayta tiklashingiz mumkin:

static bool IsAnyEndOnXAxis(Segment segment) =>
    segment is { Start.Y: 0 } or { End.Y: 0 };
Enter fullscreen mode Exit fullscreen mode

Usha gap uncha chunmagan bosela mamittan ko'rvorurasila property pattern!

💖 💪 🙅 🚩
nuriddin321
Nuriddin

Posted on May 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related