ویرگول
ورودثبت نام
soheil moonesi
soheil moonesi
خواندن ۱ دقیقه·۷ ماه پیش

C# base

کی و کجا باید از base استفاده کرد؟

The base keyword is used to access members of the base class from within a derived class. Use it if you want to:

  • Call a method on the base class that has been overridden by another method.
  • Specify which base-class constructor should be called when creating instances of the derived class.

کلمه کلیدی base به ما قابلیت این رو میده که از داخل کلاس مشتق شده بتونیم به اجزا کلاس base که override شده دسترسی پیدا کنیم.

چون اگر به خاطرتون باشه ما در حالت عادی به تمام اجزای کلاس بیس دسترسی داریم ولی وقتی که یه متد کلاس بیس توسط یه کلاس مشتق override کردیم باید از base استفاده کنیم تا به اجزا کلاس بیس دسترسی پیدا کنیم.

به طور مثال:

public class Person{ protected string ssn = &quot444-55-6666&quot protected string name = &quotJohn L. Malgraine&quot public virtual void GetInfo() { Console.WriteLine(&quotName: {0}&quot, name); Console.WriteLine(&quotSSN: {0}&quot, ssn); } } class Employee : Person { public string id = &quotABC567EFG&quot public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); Console.WriteLine(&quotEmployee ID: {0}&quot, id); } } class TestClass{ static void Main() { Employee E = new Employee(); E.GetInfo(); } } /* Output Name: John L. Malgraine SSN: 444-55-6666 Employee ID: ABC567EFG */

خوب حالا بیایم این مثال رو بررسی کنیم، همونطوری که میبینید اینجا متد GetInfo توسط کلاس employee اومده override شده. حالا ما میخوایم همچنان از اطلاعات اولیه کلاس بیس استفاده کنیم که برای همین توی همون متد اومدیم از base استفاده کردیم

این مطالب از این سایت گرفته شده است.

baseکلاس بیس
C# enthusiast
شاید از این پست‌ها خوشتان بیاید