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