Declaration va type patternlar haqida...

nuriddin321

Nuriddin

Posted on May 30, 2022

Declaration va type patternlar haqida...

Biz ifodaning ish vaqti turi berilgan turga mos kelishini tekshirish uchun declaration va type patternlardan foydalanamiz.Deklaratsiya namunasi ifodaga mos kelganda, quyidagi misolda ko'rsatilganidek, bu o'zgaruvchiga aylantirilgan ifoda natijasi tayinlanadi:

object greeting = "Hello, World!";
if (greeting is string message)
{
    Console.WriteLine(message.ToLower());  // output: hello, world!
}
Enter fullscreen mode Exit fullscreen mode
int? xNullable = 7;
int y = 23;
object yBoxed = y;
if (xNullable is int a && yBoxed is int b)
{
    Console.WriteLine(a + b);  // output: 30
}
Enter fullscreen mode Exit fullscreen mode

Agar biz faqat ifodani turini tekshirmoqchi bo'lsak, u holda o'zgaruvchi nomi o'rniga discard_ dan foydalanishimiz mumkin:

public abstract class Vehicle {}
public class Car : Vehicle {}
public class Truck : Vehicle {}

public static class TollCalculator
{
    public static decimal CalculateToll(this Vehicle vehicle) => vehicle switch
    {
        Car _ => 2.00m,
        Truck _ => 7.50m,
        null => throw new ArgumentNullException(nameof(vehicle)),
        _ => throw new ArgumentException("Unknown type of a vehicle", nameof(vehicle)),
    };
}
Enter fullscreen mode Exit fullscreen mode

C# 9.0 dan boshlab, bu maqsadda siz quyidagi misolda ko'rsatilganidek, Type patterndan foydalanishingiz mumkin:

public static decimal CalculateToll(this Vehicle vehicle) => vehicle switch
{
    Car => 2.00m,
    Truck => 7.50m,
    null => throw new ArgumentNullException(nameof(vehicle)),
    _ => throw new ArgumentException("Unknown type of a vehicle", nameof(vehicle)),
};
Enter fullscreen mode Exit fullscreen mode

Deklaratsiya namunasi kabi, type patternda ifoda natijasi null bo'lmaganda va uning ish vaqti turi yuqorida sanab o'tilgan shartlarning istalganiga javob berganda ifodaga mos keladi. Shuningdek, siz ushbu naqshni aniq, qisqacha null tekshiruvi uchun ishlatishingiz mumkin:

if (input is not null)
{
    Console.WriteLine(input);
} else
{
    throw new ArgumentNullException(paramName: nameof(input), message: "Input should not be null");
}

Enter fullscreen mode Exit fullscreen mode

Qo'shimcha ma'lumot olish uchun declaration pattern va type pattern bo'limlariga qarang.

💖 💪 🙅 🚩
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

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024