C# 类成员
类成员
类中的字段和方法通常被称为“类成员”。
示例
创建一个 Car
类,包含三个类成员:两个字段和一个方法。
// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Fields
在上一章中,您了解到类中的变量称为字段,并且可以通过创建类的对象并使用点语法(.
)来访问它们。
以下示例将创建一个名为 myObj
的 Car
类对象。然后,我们将打印 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
的。并且请记住,我们使用方法的名称后跟两个括号 ()
和一个分号 ;
来调用(执行)该方法。
示例
class Car
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
Car myObj = new Car();
myObj.fullThrottle(); // Call the method
}
}
为什么我们将方法声明为 public
,而不是像C# 方法章节中的示例那样声明为 static
?
原因很简单:static
方法可以在不创建类的对象的情况下进行访问,而 public
方法只能由对象访问。
使用多个类
请记住,从上一章开始,我们可以使用多个类以获得更好的组织(一个用于字段和方法,另一个用于执行)。这是推荐的做法。
prog2.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!");
}
}
prog.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
)访问。
您将在后面的章节中了解更多关于访问修饰符的内容。