C#中私有構(gòu)造函數(shù)的特點(diǎn)和用途實(shí)例解析
本文以實(shí)例形式分析私有構(gòu)造函數(shù)的特點(diǎn),以及在何種情況下使用私有構(gòu)造函數(shù)。相信對(duì)于大家更好的理解C#中的私有構(gòu)造函數(shù)有一定的促進(jìn)作用。具體如下:
一、帶私有構(gòu)造函數(shù)的類不能被繼承
在Animal類中聲明一個(gè)私有構(gòu)造函數(shù),讓Dog類來繼承Animal類。
public class Animal { private Animal() { Console.WriteLine("i am animal"); } } public class Dog : Animal { }
運(yùn)行程序,生成解決方案,報(bào)錯(cuò)如下圖所示:
二、帶私有構(gòu)造函數(shù)的類不能被實(shí)例化
運(yùn)行如下測試代碼:
class Program { static void Main(string[] args) { Animal animal = new Animal(); } } public class Animal { private Animal() { Console.WriteLine("i am animal"); } }
程序運(yùn)行后生成解決方案,報(bào)錯(cuò)如下圖所示:
三、私有構(gòu)造函數(shù)的應(yīng)用
有些時(shí)候,我們不希望一個(gè)類被過多地被實(shí)例化,比如有關(guān)全局的類、路由類等。這時(shí)候,我們可以為類設(shè)置構(gòu)造函數(shù)并提供靜態(tài)方法。
class Program { static void Main(string[] args) { string str = Animal.GetMsg(); Console.WriteLine(str); Console.ReadKey(); } } public class Animal { private Animal() { Console.WriteLine("i am animal"); } public static string GetMsg() { return "Hello World"; } }
總結(jié):一旦一個(gè)類被設(shè)置成私有構(gòu)造函數(shù),就不能被繼承,不能被實(shí)例化,這種情況下,通常為類提供靜態(tài)方法以供調(diào)用。
相關(guān)文章
C# 在PDF文檔中創(chuàng)建表格的實(shí)現(xiàn)方法
表格能夠一目了然的讓用戶看到數(shù)據(jù)信息,使信息顯得有條理化,那么在pdf類型的文檔中如何來添加表格并對(duì)表格進(jìn)行格式化操作呢?下面小編給大家?guī)砹薈# 在PDF文檔中創(chuàng)建表格的實(shí)現(xiàn)方法,需要的朋友參考下吧2017-12-12淺析c#范型中的特殊關(guān)鍵字where & default
以下是對(duì)c#范型中的特殊關(guān)鍵字where和default進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下2013-09-09