ParentClass
namespace ConstructorDemo
{
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("Parent base Constructor");
}
public ParentClass (string Name)
{
Console.WriteLine("Hello {0} From ParentClass" , Name);
}
}
}
ChildClassnamespace ConstructorDemo
{
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("Child base Constructor");
}
// Demo1
// 當 ChildClass 被 new 時,預設是會觸發 ParentClass 的 base Constructor
public ChildClass(string Name)
{
Console.WriteLine("Hello {0} from ChildClass", Name);
}
// Demo2
// 指定觸發 ParenClass Constructor
public ChildClass(string Name) : base (Name)
{
Console.WriteLine("Hello {0} from ChildClass", Name);
}
}
}
測試namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
ChildClass c1 = new ChildClass();
Console.WriteLine("------------------------------");
ChildClass c2 = new ChildClass("路人");
}
}
}
Demo1:沒有指定父類別建構子的情況Demo2:指定父類別建構子
之前的觀念不知哪裡來的,Orz
- 延伸閱讀
- [C#] 呼叫父建構子
- 參考資料
- Zoom 遠距教學
沒有留言:
張貼留言