###### tags: `C#` # this 與 base ## this * 透過 this 關鍵字可以直接存取所屬物件的屬性與方法,常用於 method 的參數名稱與屬性名稱重複的時候。base 關鍵字也是類似原理,只是 base 存取的對象是基底類別 (base class) ```csharp= class Fruits { private string type = "香蕉"; //私有變數與方法參數名稱相同 public void GetFruit(string type) { Console.WriteLine(type); //顯示:芭樂 Console.WriteLine(this.type); //顯示:香蕉 } } class Program { static void Main(string[] args) { Fruits fruits = new Fruits(); fruits.GetFruit("芭樂"); } } ``` ## base * 當衍生類別中出現了名稱相同的屬性,若想存取基底類別中的屬性而非衍生類別的屬性,就可以使用 base 來存取 ```csharp= class Fruits { protected string type = "水果"; } class Apple : Fruits { private string type = "蘋果"; public Apple() { //用 base 存取基底類別變數 Console.WriteLine(base.type); //顯示:水果 Console.WriteLine(type); //顯示:蘋果 } } class Program { static void Main(string[] args) { Apple apple = new Apple(); } } ``` * 當衍生類別 override 了一個基底類別的 method,若想存取原版 (原本在基底類別內的版本) 的 method,就可以用 base ```csharp= class Fruits { private string type = "水果"; public virtual void GetFruit() { Console.WriteLine("基底類別:" + type); } } class Apple : Fruits { private string type = "蘋果"; public override void GetFruit() { //用 base 存取基底類別方法 base.GetFruit(); //顯示:基底類別:水果 Console.WriteLine("衍生類別:" + type); //顯示:衍生類別:蘋果 } } class Program { static void Main(string[] args) { Apple apple = new Apple(); apple.GetFruit(); } } ``` * 想要呼叫基底類別的建構子 (constructor) 時,可以在自己的建構子後加上 base 來呼叫 ```csharp= class Fruits { public Fruits(string type) { Console.WriteLine("基底類別:" + type); } } class Apple : Fruits { private string type = "蘋果"; //用 base 存取基底類別建構子 public Apple(string type) : base(type) { Console.WriteLine("衍生類別:" + this.type); //顯示:衍生類別:蘋果 } } class Program { static void Main(string[] args) { Apple apple = new Apple("水果"); //顯示:基底類別:水果 } } ``` > 參考資料 * [小山的 C# 教學-Base 關鍵字](https://www.youtube.com/watch?v=1eAGN-NPBXE) * [C# base 和 this 的區別](https://www.796t.com/content/1544002264.html) * [C# this 和 base](http://notepad.yehyeh.net/Content/CSharp/CH01/03ObjectOrient/5thisAndBase/index.php)