当前位置: 移动技术网 > IT编程>开发语言>c# > C# 类的声明详解

C# 类的声明详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

访问修饰符 class 类名 
 { 
 //类成员:
 // methods, properties, fields, events, delegates 
 // and nested classes go here. 
 }

一个类应包括:

  • 类名
  • 成员
  • 特征

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

  • 构造函数
  • 析构函数
  • 常量
  • 字段
  • 方法
  • 属性
  • 索引器
  • 运算符
  • 事件
  • 委托
  • 接口
  • 结构

示例:

下面的示例说明如何声明类的字段、构造函数和方法。 该例还说明了如何实例化对象及如何打印实例数据。 在此例中声明了两个类,一个是 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 

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

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

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

备注:

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

inheritance 示例
class classa { }
single class derivedclass: baseclass { }
无,实现两个接口 class implclass: iface1, iface2 { }
单一,实现一个接口 class implderivedclass: baseclass, iface1 { }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网