//基類 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVATwentyQuestions { class Test { public string _name = ""; public Test(string name) { _name = name; } public virtual void ConvertToUpper() { _name = _name.ToUpper(); } } } //子類 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVATwentyQuestions { class InheritTest : Test { //base("NewName"); //錯誤的調用,所以注釋 //繼承基類的構造器 public InheritTest(string name) : base(name) { } //繼承基類的構造器,傳入該構造器的參數為一個值的方法 public InheritTest(string name) : base(ModifyBase(name)) { } private static string ModifyBase(string newName) { return newName.ToUpper(); } } } //主方法 static void Main(string[] args) { Console.WriteLine(); Test nTest = new Test("Base"); Console.WriteLine(nTest._name); InheritTest iTest = new InheritTest("NewName"); Console.WriteLine(iTest._name); }
繼承基類的構造器
結果:
Base
NewName
繼承基類的構造器,傳入該構造器的參數為一個值的方法
結果:
Base
NEWNAME