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!
}
int? xNullable = 7;
int y = 23;
object yBoxed = y;
if (xNullable is int a && yBoxed is int b)
{
Console.WriteLine(a + b); // output: 30
}
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)),
};
}
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)),
};
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");
}
Qo'shimcha ma'lumot olish uchun declaration pattern va type pattern bo'limlariga qarang.
Top comments (0)