C# 类成员

类成员

类中的字段和方法通常称为"类成员":

实例

创建一个包含三个类成员的Car类:两个字段和一个方法。

// 类
class MyClass
{
  // 类成员
  string color = "red";        // 字段
  int maxSpeed = 200;          // 字段
  public void fullThrottle()   // 方法
  {
    Console.WriteLine("The car is going as fast as it can!");
  }
}

字段

在上一章中,您了解到类中的变量称为字段,您可以通过创建类的对象和使用点语法(.)来访问它们。

下面的示例将创建一个名为myObjCar类对象。然后打印颜色color和最大速度maxSpeed字段的值:

实例

class Car 
{
  string color = "red";
  int maxSpeed = 200;

  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.color);
    Console.WriteLine(myObj.maxSpeed);
  }
}

运行实例 »

也可以将字段保留为空,并在创建对象时对其进行修改:

实例

class Car 
{
  string color;
  int maxSpeed;

  static void Main(string[] args)
  {
    Car myObj = new Car();
    myObj.color = "red";
    myObj.maxSpeed = 200;
    Console.WriteLine(myObj.color);
    Console.WriteLine(myObj.maxSpeed);
  }
}

运行实例 »

这在创建一个类的多个对象时特别有用:

实例

class Car 
{
  string model;
  string color;
  int year;

  static void Main(string[] args)
  {
    Car Ford = new Car();
    Ford.model = "Mustang";
    Ford.color = "red";
    Ford.year = 1969;

    Car Opel = new Car();
    Opel.model = "Astra";
    Opel.color = "white";
    Opel.year = 2005;

    Console.WriteLine(Ford.model);
    Console.WriteLine(Opel.model);
  }
}

运行实例 »



对象方法

您从C# 方法一章中了解到,方法用于执行某些操作。

方法通常属于类,它们定义类的对象的行为方式。

与字段一样,可以使用点语法访问方法。但是请注意,该方法必须是公共的public。请记住,我们使用方法的名称后跟两个paranthese()和一个分号;来调用(执行)该方法:

实例

class Car 
{
  string color;                 // 字段
  int maxSpeed;                 // 字段
  public void fullThrottle()    // 方法
  {
    Console.WriteLine("The car is going as fast as it can!"); 
  }

  static void Main(string[] args)
  {
    Car myObj = new Car();
    myObj.fullThrottle();  // 调用方法
  }
}

运行实例 »

为什么我们要声明这个方法是公共的public,而不是静态的static,就像C#方法一章中的例子一样C# Methods Chapter?

原因很简单:不创建类的对象就可以访问静态方法static,而公共方法public只能由对象访问。


使用多个类

记住上一章,我们可以使用多个类来更好地组织(一个用于字段和方法,另一个用于执行)。建议:

Car.cs

class Car 
{
  public string model;
  public string color;
  public int year;
  public void fullThrottle()
  {
    Console.WriteLine("The car is going as fast as it can!"); 
  }
}

Program.cs

class Program
{
  static void Main(string[] args)
  {
    Car Ford = new Car();
    Ford.model = "Mustang";
    Ford.color = "red";
    Ford.year = 1969;

    Car Opel = new Car();
    Opel.model = "Astra";
    Opel.color = "white";
    Opel.year = 2005;

    Console.WriteLine(Ford.model);
    Console.WriteLine(Opel.model);
  }
}

运行实例 »

public关键字称为访问修饰符,它指定Car的字段对于其他类(如 Program)也是可访问的。

在后面的章节中,您将了解更多有关访问修饰符的信息。

提示: 在继续阅读的过程中,您还将进一步了解其他类成员,例如构造函数属性