类是运用关键字 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 { } |
以上就是C#类的声明详解及实例的细致内容,更多请关注ki4网别的相干文章!