C#类的声明详解及实例


本文摘自PHP中文网,作者黄舟,侵删。

本文主要对C# 类的声明进行详细介绍。具有一定的参考价值,下面跟着小编一起来看下吧

类是使用关键字 class 声明的,如下面的示例所示:

1

2

3

4

5

6

访问修饰符 class 类名

 {

 //类成员:

 // Methods, properties, fields, events, delegates

 // and nested classes go here.

 }

一个类应包括:

  • 类名

  • 成员

  • 特征

一个类可包含下列成员的声明:

  • 构造函数

  • 析构函数

  • 常量

  • 字段

  • 方法

  • 属性

  • 索引器

  • 运算符

  • 事件

  • 委托

  • 接口

  • 结构

示例:

下面的示例说明如何声明类的字段、构造函数和方法。 该例还说明了如何实例化对象及如何打印实例数据。 在此例中声明了两个类,一个是 Child类,它包含两个私有字段(name 和 age)和两个公共方法。 第二个类 StringTest 用来包含 Main。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

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 的名称:

1

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

只有当 Child 是 Main 的成员时,才能从 Main 访问该类的私有成员。

类型声明在选件类中,不使用访问修饰符默认为 private,因此,在此示例中的数据成员会 private,如果移除了关键字。

最后要注意的是,默认情况下,对于使用默认构造函数 (child3) 创建的对象,age 字段初始化为零。

备注:

类在 c# 中是单继承的。 也就是说,类只能从继承一个基类。 但是,一个类可以实现一个以上的(一个或多个)接口。 下表给出了类继承和接口实现的一些示例:

Inheritance示例
class ClassA { }
Singleclass DerivedClass: BaseClass { }
无,实现两个接口class ImplClass: IFace1, IFace2 { }
单一,实现一个接口class ImplDerivedClass: BaseClass, IFace1 { }

以上就是C#类的声明详解及实例的详细内容!

相关阅读 >>

详解C#winform程序的toolstripbutton自定义背景应用示例源码

C#基于正则表达式抓取a标签链接和innerhtml的方法

C#获取系统当前鼠标的图案示例代码

C#使用newtonsoft的json.net进行对象的序列化与反序列化

详解C#读取xml多级子节点的示例代码

C#如何导入导出与处理excel文件

C# 如何设置系统的默认打印机的简单代码示例

C#将unicode编码转换为汉字字符串的代码分析

关于C#中string类型的方法分享

C# tabcontral选项卡中加载显示窗体后 实现单向参数传递测试代码示例(图)

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...