Csharp 简明教程

C

当您定义一个类时,您定义了数据类型的一个蓝图。这实际上并未定义任何数据,但它确实定义了类名称的含义。也就是说,类对象由什么组成以及可以在该对象上执行什么操作。对象是类的实例。构成类的函数和变量称为类的成员。

When you define a class, you define a blueprint for a data type. This does not actually define any data, but it does define what the class name means. That is, what an object of the class consists of and what operations can be performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class.

Defining a Class

类定义以关键字 class 开头,后跟类名称;类主体用一对大括号括起来。以下是类定义的一般形式 −

A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. Following is the general form of a class definition −

<access specifier> class  class_name {
   // member variables
   <access specifier> <data type> variable1;
   <access specifier> <data type> variable2;
   ...
   <access specifier> <data type> variableN;
   // member methods
   <access specifier> <return type> method1(parameter_list) {
      // method body
   }
   <access specifier> <return type> method2(parameter_list) {
      // method body
   }
   ...
   <access specifier> <return type> methodN(parameter_list) {
      // method body
   }
}

请注意 −

Note −

  1. Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private.

  2. Data type specifies the type of variable, and return type specifies the data type of the data the method returns, if any.

  3. To access the class members, you use the dot (.) operator.

  4. The dot operator links the name of an object with the name of a member.

以下示例说明迄今为止所讨论的概念:

The following example illustrates the concepts discussed so far −

using System;

namespace BoxApplication {
   class Box {
      public double length;   // Length of a box
      public double breadth;  // Breadth of a box
      public double height;   // Height of a box
   }
   class Boxtester {
      static void Main(string[] args) {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();   // Declare Box2 of type Box
         double volume = 0.0;    // Store the volume of a box here

         // box 1 specification
         Box1.height = 5.0;
         Box1.length = 6.0;
         Box1.breadth = 7.0;

         // box 2 specification
         Box2.height = 10.0;
         Box2.length = 12.0;
         Box2.breadth = 13.0;

         // volume of box 1
         volume = Box1.height * Box1.length * Box1.breadth;
         Console.WriteLine("Volume of Box1 : {0}",  volume);

         // volume of box 2
         volume = Box2.height * Box2.length * Box2.breadth;
         Console.WriteLine("Volume of Box2 : {0}", volume);
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Volume of Box1 : 210
Volume of Box2 : 1560

Member Functions and Encapsulation

类的一个成员函数是一个在其定义或原型中具有与其它的变量相似的类定义中的函数。它对类中的任何对象起作用,并且对于该对象,可以访问类的所有成员。

A member function of a class is a function that has its definition or its prototype within the class definition similar to any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.

成员变量是一个对象(从设计的角度来说)的属性,并且它们被保密以便实现封装。只能使用公共成员函数来访问这些变量。

Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.

让我们把上述概念用于在一个类中设置和获取不同类成员的值:

Let us put above concepts to set and get the value of different class members in a class −

using System;

namespace BoxApplication {
   class Box {
      private double length;   // Length of a box
      private double breadth;  // Breadth of a box
      private double height;   // Height of a box

      public void setLength( double len ) {
         length = len;
      }
      public void setBreadth( double bre ) {
         breadth = bre;
      }
      public void setHeight( double hei ) {
         height = hei;
      }
      public double getVolume() {
         return length * breadth * height;
      }
   }
   class Boxtester {
      static void Main(string[] args) {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;

         // Declare Box2 of type Box
         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Volume of Box1 : 210
Volume of Box2 : 1560

C

一个类 constructor 是一个类的特殊成员函数,每当我们创建一个新的该类的对象时它都会执行。

A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

构造函数的名称与类相同,且它没有任何返回类型。以下示例说明构造函数的概念:

A constructor has exactly the same name as that of class and it does not have any return type. Following example explains the concept of constructor −

using System;

namespace LineApplication {
   class Line {
      private double length;   // Length of a line

      public Line() {
         Console.WriteLine("Object is being created");
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }

      static void Main(string[] args) {
         Line line = new Line();

         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Object is being created
Length of line : 6

一个 default constructor 没有任何参数,但是如果需要的话,构造函数可能会有参数。此类构造函数被称为 parameterized constructors 。这种技术可以帮助你在创建对象时给它分配一个初始值,如以下示例所示:

A default constructor does not have any parameter but if you need, a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example −

using System;

namespace LineApplication {
   class Line {
      private double length;   // Length of a line

      public Line(double len) {  //Parameterized constructor
         Console.WriteLine("Object is being created, length = {0}", len);
         length = len;
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }
      static void Main(string[] args) {
         Line line = new Line(10.0);
         Console.WriteLine("Length of line : {0}", line.getLength());

         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Object is being created, length = 10
Length of line : 10
Length of line : 6

C

一个 destructor 是个类的特殊成员函数,每当这个类的对象超出了范围,它都会执行。一个 destructor 的名称与类的名称完全相同,并带有一个前缀波浪号 (~),并且它既不能返回一个值,又不能接收任何参数。

A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope. A destructor has exactly the same name as that of the class with a prefixed tilde (~) and it can neither return a value nor can it take any parameters.

析构函数对于在退出程序之前释放内存资源非常有用。析构函数不能被继承或重载。

Destructor can be very useful for releasing memory resources before exiting the program. Destructors cannot be inherited or overloaded.

以下示例说明析构函数的概念:

Following example explains the concept of destructor −

using System;

namespace LineApplication {
   class Line {
      private double length;   // Length of a line

      public Line() {   // constructor
         Console.WriteLine("Object is being created");
      }
      ~Line() {   //destructor
         Console.WriteLine("Object is being deleted");
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }
      static void Main(string[] args) {
         Line line = new Line();

         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Object is being created
Length of line : 6
Object is being deleted

Static Members of a C

我们可以使用 static 关键字将类成员定义为 static。当我们将类的成员声明为 static 时,这意味着无论创建了多少个类的对象,static 成员只有一个副本。

We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.

关键字 static 意味着类只有一个成员实例。静态变量用于定义常量,因为可以通过调用类来检索其值,而无需创建类的实例。可以在成员函数或类定义之外初始化静态变量。也可以在类定义中初始化静态变量。

The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.

以下示例演示了 static variables 的使用 −

The following example demonstrates the use of static variables

using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }
      public int getNum() {
         return num;
      }
   }
   class StaticTester {
      static void Main(string[] args) {
         StaticVar s1 = new StaticVar();
         StaticVar s2 = new StaticVar();

         s1.count();
         s1.count();
         s1.count();

         s2.count();
         s2.count();
         s2.count();

         Console.WriteLine("Variable num for s1: {0}", s1.getNum());
         Console.WriteLine("Variable num for s2: {0}", s2.getNum());
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Variable num for s1: 6
Variable num for s2: 6

还可以将 member function 声明为 static 。此类函数只能访问静态变量。静态函数甚至在创建对象之前就存在。以下示例演示了 static functions 的使用 −

You can also declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created. The following example demonstrates the use of static functions

using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }
      public static int getNum() {
         return num;
      }
   }
   class StaticTester {
      static void Main(string[] args) {
         StaticVar s = new StaticVar();

         s.count();
         s.count();
         s.count();

         Console.WriteLine("Variable num: {0}", StaticVar.getNum());
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Variable num: 3