C# 类 class
类是使用关键字 class 声明的,如下面的示例所示:
class TestClass { // Methods, properties, fields, events, delegates // and nested classes go here. }
下面的示例说明如何声明类的字段、构造函数和方法。该例还说明了如何实例化对象及如何打印实例数据。在此例中声明了两个类,一个是 Child 类,它包含两个私有字段(name 和 age)和两个公共方法。第二个类 TestClass 用来包含 Main。
class Child { private int age; private string name; // Default constructor: public Child() { name = "N/A"; } // 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