الصنف = قالب
class Car
{
public string Brand; // حقل
public int Speed;
public void Drive() // دالة
{
Console.WriteLine($"{Brand} تسير بسرعة {Speed}");
}
}
إنشاء كائن
Car myCar = new Car();
myCar.Brand = "تويوتا";
myCar.Speed = 120;
myCar.Drive();
تهيئة بالكائن (Object Initializer)
Car c = new Car { Brand = "هوندا", Speed = 100 };
this
تشير للكائن الحالي:
class Car
{
public string Brand;
public void SetBrand(string Brand)
{
this.Brand = Brand; // تمييز الحقل عن المعامل
}
}
الأعضاء الساكنة (static)
تنتمي للصنف لا للكائن:
class Counter
{
public static int Count = 0;
}
Counter.Count++; // بلا إنشاء كائن
أخطاء شائعة
- نسيان
newعند إنشاء الكائن. - نسيان
publicفيبقى العضو خاصًّا افتراضيًّا.
🎯 التالي: المُنشئات والخصائص (Properties).