国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C# 類的聲明詳解

2020-01-24 00:50:01
字體:
供稿:網(wǎng)友

類是使用關(guān)鍵字 class 聲明的,如下面的示例所示:

訪問修飾符 class 類名  {  //類成員: // Methods, properties, fields, events, delegates  // and nested classes go here.  }

一個類應(yīng)包括:

  • 類名
  • 成員
  • 特征

一個類可包含下列成員的聲明:

  • 構(gòu)造函數(shù)
  • 析構(gòu)函數(shù)
  • 常量
  • 字段
  • 方法
  • 屬性
  • 索引器
  • 運(yùn)算符
  • 事件
  • 委托
  • 接口
  • 結(jié)構(gòu)

示例:

下面的示例說明如何聲明類的字段、構(gòu)造函數(shù)和方法。 該例還說明了如何實例化對象及如何打印實例數(shù)據(jù)。 在此例中聲明了兩個類,一個是 Child類,它包含兩個私有字段(name 和 age)和兩個公共方法。 第二個類 StringTest 用來包含 Main。

class Child { private int age; private string name; // Default constructor: public Child() { name = "Lee"; } // Constructor: public Child(string name, int age) { this.name = name; this.age = age; } // Printing method: public void PrintChild() { Console.WriteLine("{0}, {1} years old.", name, age); } } class StringTest { static void Main() { // Create objects by using the new operator: Child child1 = new Child("Craig", 11); Child child2 = new Child("Sally", 10); // Create an object using the default constructor: Child child3 = new Child(); // Display results: Console.Write("Child #1: "); child1.PrintChild(); Console.Write("Child #2: "); child2.PrintChild(); Console.Write("Child #3: "); child3.PrintChild(); } } /* Output: Child #1: Craig, 11 years old. Child #2: Sally, 10 years old. Child #3: N/A, 0 years old. */

注意:在上例中,私有字段(name 和 age)只能通過 Child 類的公共方法訪問。 例如,不能在 Main 方法中使用如下語句打印 Child 的名稱:

Console.Write(child1.name);   // Error 

只有當(dāng) Child 是 Main 的成員時,才能從 Main 訪問該類的私有成員。

類型聲明在選件類中,不使用訪問修飾符默認(rèn)為 private,因此,在此示例中的數(shù)據(jù)成員會 private,如果移除了關(guān)鍵字。

最后要注意的是,默認(rèn)情況下,對于使用默認(rèn)構(gòu)造函數(shù) (child3) 創(chuàng)建的對象,age 字段初始化為零。

備注:

類在 c# 中是單繼承的。 也就是說,類只能從繼承一個基類。 但是,一個類可以實現(xiàn)一個以上的(一個或多個)接口。 下表給出了類繼承和接口實現(xiàn)的一些示例:

Inheritance 示例
class ClassA { }
Single class DerivedClass: BaseClass { }
無,實現(xiàn)兩個接口 class ImplClass: IFace1, IFace2 { }
單一,實現(xiàn)一個接口 class ImplDerivedClass: BaseClass, IFace1 { }

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持武林網(wǎng)!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 常熟市| 山丹县| 二连浩特市| 什邡市| 开鲁县| 远安县| 湘乡市| 正镶白旗| 库尔勒市| 高淳县| 陆川县| 上犹县| 巴南区| 临城县| 濮阳县| 福州市| 抚松县| 沙河市| 寻甸| 庐江县| 海伦市| 阳泉市| 乌鲁木齐县| 辰溪县| 伊春市| 加查县| 南陵县| 富蕴县| 即墨市| 乌拉特中旗| 紫阳县| 绥化市| 绥中县| 荣昌县| 金川县| 金乡县| 肥城市| 鲜城| 财经| 思南县| 洮南市|