C# 繼承(4)
阿新 • • 發佈:2018-06-21
報錯 提示 clas PE ron bsp http 調用父類 spa
接上章:
class NameList { public NameList() => Console.WriteLine("這個是NameList的構造函數"); public NameList(string Name) => Console.WriteLine($"這個是NameList的重載構造函數,輸入的參數是{Name}"); ~NameList() => Debug.WriteLine("釋放NameList"); public string Name { get; set; }public void ID() => Console.WriteLine($"我的id是{Name}"); } class A : NameList { public A() : base() => Console.WriteLine("這是A類的初始化,也就是構造函數"); public A(string Name) : base(Name) =>Console.WriteLine($"這個是A的重載構造函數,輸入的參數是{Name}"); ~A() => Debug.WriteLine("釋放A"); } class B : NameList { public B() : base() => Console.WriteLine("這是A類的初始化,也就是構造函數"); public B(string Name) => Console.WriteLine($"這個是B的重載構造函數,輸入的參數是{Name}"); ~B() => Debug.WriteLine("釋放B"); }
這一章 我們來說說 繼承的方法和方法隱藏。
我們來修改代碼:
這個代碼比較尬,主要是演示子類中的方法使用父類的方法。
A類的ShowType方法使用NameList的Show<T>(T type)方法。
class NameList { public NameList() => Console.WriteLine("這個是NameList的構造函數"); public NameList(string Name) => Console.WriteLine($"這個是NameList的重載構造函數,輸入的參數是{Name}"); ~NameList() => Debug.WriteLine("釋放NameList"); public string Name { get; set; } public void ID() => Console.WriteLine($"我的id是{Name}"); public void Show<T>(T type) where T : NameList => Console.WriteLine(type.GetType().FullName);//泛型方法 } class A : NameList { public A() : base() => Console.WriteLine("這是A類的初始化,也就是構造函數"); public A(string Name) : base(Name) =>Console.WriteLine($"這個是A的重載構造函數,輸入的參數是{Name}"); ~A() => Debug.WriteLine("釋放A"); public void ShowType() => base.Show<A>(this); } class B : NameList { public B() : base() => Console.WriteLine("這是A類的初始化,也就是構造函數"); public B(string Name) => Console.WriteLine($"這個是B的重載構造函數,輸入的參數是{Name}"); ~B() => Debug.WriteLine("釋放B"); }
實例化代碼:
new A().ShowType();
結果
上述代碼主要是說子類調用父類的方法,使用Base關鍵字。當然父類的方法必須是公共的方法。
上面的代碼還是比較尬的,趕緊進入下一個環節 繼承的隱藏方法
我們先修改代碼:
在A類中添加一個名為ID的方法。此時A類有自己的ID方法和繼承NameList的ID方法。
class NameList { public NameList() => Console.WriteLine("這個是NameList的構造函數"); public NameList(string Name) => Console.WriteLine($"這個是NameList的重載構造函數,輸入的參數是{Name}"); ~NameList() => Debug.WriteLine("釋放NameList"); public string Name { get; set; } public void ID() => Console.WriteLine($"我的id是{Name}"); public void Show<T>(T type) where T : NameList => Console.WriteLine(type.GetType().FullName); } class A : NameList { public A() : base() => Console.WriteLine("這是A類的初始化,也就是構造函數"); public A(string Name) : base(Name) =>Console.WriteLine($"這個是A的重載構造函數,輸入的參數是{Name}"); ~A() => Debug.WriteLine("釋放A"); public void ShowType() => base.Show<A>(this); public void ID() => Console.WriteLine("這個ID方法是A類"); } class B : NameList { public B() : base() => Console.WriteLine("這是A類的初始化,也就是構造函數"); public B(string Name) => Console.WriteLine($"這個是B的重載構造函數,輸入的參數是{Name}"); ~B() => Debug.WriteLine("釋放B"); }
實例化:
new A().ID();
結果
結果是使用的A類專屬的ID方法,不再使用繼承的ID方法。
但是看代碼
會提示報錯,為什麽?
因為子類的方法和父類的方法是相同。有可能會報錯。
C# 繼承(4)