
عملگر is:
عملگر is برای بررسی نوع (Type Checking) استفاده میشود. مثل این میماند که بپرسیم: "آیا این شیء از این نوع است؟"
ساختار ساده:
if (variable is TypeName) { // اگر variable از نوع TypeName باشد }
object obj = "Hello"; if (obj is string) { Console.WriteLine("It's a string!"); // خروجی: It's a string! } if (obj is int) { Console.WriteLine("It's an integer!"); // اجرا نمیشود }
مثال دیگر:
public class Animal { } public class Dog : Animal { } public class Cat : Animal { } Animal myPet = new Dog(); if (myPet is Dog) { Console.WriteLine("It's a dog! 🐶"); } if (myPet is Cat) { Console.WriteLine("It's a cat! 🐱"); // اجرا نمیشود }
کلیدواژه base:
کلمه base برای دسترسی به اعضای کلاس پایه (پدر) از داخل کلاس فرزند استفاده میشود.
مثال:
public class Animal { public string Name { get; } public Animal(string name) { Name = name; Console.WriteLine($"Animal created: {name}"); } } public class Dog : Animal { public string Breed { get; } public Dog(string name, string breed) : base(name) // ✅ فراخوانی سازنده Animal { Breed = breed; Console.WriteLine($"Dog breed: {breed}"); } } // استفاده var dog = new Dog("Rex", "German Shepherd"); // خروجی: // Animal created: Rex // Dog breed: German Shepherd
فراخوانی متدهای کلاس پایه (وقتی متد override شده)
مثال:
public class Vehicle { public virtual void Start() { Console.WriteLine("Vehicle is starting..."); } } public class Car : Vehicle { public override void Start() { base.Start(); // ✅ فراخوانی متد Start کلاس Vehicle Console.WriteLine("Car engine is running!"); } } // استفاده var car = new Car(); car.Start(); // خروجی: // Vehicle is starting... // Car engine is running!
دسترسی به پراپرتیهای کلاس پایه
مثال:
// استفاده var manager = new Manager(); Console.WriteLine($"Total salary: {manager.CalculateTotalSalary()}"); // خروجی: Total salary: 1500 public class Employee { protected decimal BaseSalary = 1000; // protected: فقط کلاسهای فرزند میبینند } public class Manager : Employee { public decimal CalculateTotalSalary() { decimal bonus = 500; return base.BaseSalary + bonus; // ✅ دسترسی به BaseSalary از کلاس Employee } }
در متدهای static قابل استفاده نیست
مثال:
public class Parent { public static void Method() { } } public class Child : Parent { public static void MyMethod() { // base.Method(); // ❌ خطا! base در static معنی ندارد } }
Telegram: @CaKeegan
Gmail : amidgm2020@gmail.com