C# 派生类的构造函数
生活随笔
收集整理的這篇文章主要介紹了
C# 派生类的构造函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
假定沒有為任何類定義任何顯式的構造函數,這樣編譯器就會為所有的類提供默認的初始化構
造函數,在后臺會進行許多操作,但編譯器可以很好地解決類的層次結構中的所有問題,每個類中
的每個字段都會初始化為對應的默認值。但在添加了一個我們自己的構造函數后,就要通過派生類
的層次結構高效地控制構造過程,因此必須確保構造過程順利進行,不要出現不能按照層次結構進
行構造的問題。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApplication3
{//抽象類是指設計為被繼承的類,抽象類只能用作其它類的基類,且抽象類不能被實例化abstract class GenericCustomer{private string name;/// <summary>/// 構造函數/// </summary>/// <param name="name"></param>public GenericCustomer(string name){this.name = name;}}class NeverMore60Customer : GenericCustomer{private uint highCostMinutesUsed;private string referrerName;//使用base關鍵字指定應使用基類中的哪一個構造函數public NeverMore60Customer(string name, string referrerName): base(name){this.referrerName = referrerName;}//使用this關鍵字指定應使用當前類中的哪一個構造函數public NeverMore60Customer(string name): this(name, "<None>"){}}class MyClass{readonly int firstVar;readonly double secondVar;public string UserName;public int UserIdNumber;public void Print(){Console.WriteLine(firstVar);Console.WriteLine(secondVar);}//私有構造函數執行其它構造函數共用的初始化,該構造函數//只能讓類中其它構造函數調用,而不能從類的外部調用private MyClass(){firstVar = 20;secondVar = 30.5;}public MyClass(string firstName): this(){UserName = firstName;UserIdNumber = -1;}public MyClass(int id): this(){UserName = "Anonymous";UserIdNumber = id;}public MyClass(string firstName, int userIdNumber): this(){UserName = firstName;UserIdNumber = userIdNumber;}}class Program{static void Main(string[] args){MyClass myClass = new MyClass("Jason", 1);//myClass.Print();Console.WriteLine(myClass.UserIdNumber);Console.WriteLine(myClass.UserName);}}
}
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的C# 派生类的构造函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cordova 某个页面强制横屏_小白科
- 下一篇: javascript --- [虚拟D