C# 類的聲明詳解
類是使用關(guān)鍵字 class 聲明的,如下面的示例所示:
訪問修飾符 class 類名
{
//類成員:
// Methods, properties, fields, events, delegates
// and nested classes go here.
}
一個類應(yīng)包括:
- 類名
- 成員
- 特征
一個類可包含下列成員的聲明:
- 構(gòu)造函數(shù)
- 析構(gòu)函數(shù)
- 常量
- 字段
- 方法
- 屬性
- 索引器
- 運算符
- 事件
- 委托
- 類
- 接口
- 結(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 訪問該類的私有成員。
類型聲明在選件類中,不使用訪問修飾符默認為 private,因此,在此示例中的數(shù)據(jù)成員會 private,如果移除了關(guā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í)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
C#利用FileSystemWatcher實時監(jiān)控文件的增加,修改,重命名和刪除
好多時候,我們都需要知道某些目錄下的文件什么時候被修改、刪除過等。本文將利用FileSystemWatcher實現(xiàn)實時監(jiān)控文件的增加,修改,重命名和刪除,感興趣的可以了解一下2022-08-08

