解释C#中类的概念

类是 C# 中的基本类型之一。我们可以将类视为与问题域相关的对象的蓝图。它是一个模板,我们从中创建对象,定义将从此类创建的对象集共享的结构和行为。简单来说,一个类就是一个曲奇饼,对象就是曲奇饼本身。

类还支持封装,这是面向对象编程中的一个重要概念。这意味着将数据和处理数据的操作组合在一个地方,并为该对象的用户提供一个简单的 API。一个类允许我们封装数据并对其他类隐藏不相关的细节。

We can create a class by using the class keyword, followed by the name of the class.

// 用户.cs

public class User{

   private string name;

   private int salary;

   public void Promote(){

      salary += 1000;

   }

}

In the above example, User is a class that represents the users. The class encapsulates two pieces of data − name and salary. These are known as class fields, and hold the users' name and salary. It also has a method named Promote(), which raises the user's salary.

Each class has an associated access modifier that controls whether the class will be visible to other classes. Here are the five possible values we can provide for the access modifier.

Access ModifierDescription
publicUnlimited access
protectedLimited access to the derived classes
internalLimited access to the assembly
protected internalLimited access to the assembly or the derived classes
privateNo outside access

要创建类的实例,我们可以使用new关键字。所述新运营商计算由该对象的对象的数据和分配存储器所需要的字节数。然后它返回一个指向新创建对象的指针(也称为引用)。

var alice = new User();

var bob = new User();

然后将此引用存储在 = 符号左侧的变量中。在上面的例子中,Alice 和 Bob 持有指向新创建对象的引用或指针。

在 C# 中,类的命名约定遵循 PascalCase,它将复合词中每个单词的首字母大写,例如 StringBuilder、UserController 等。不必在名称与类名匹配的文件中创建类。但是,这是大多数 C# 项目使用的约定。

构造函数

在上面的例子中,当我们创建 User 类的实例时,即 alice 和 bob,我们没有提供他们的初始姓名和薪水。通常,新创建的对象需要一些信息来完成其工作,并且使用构造函数来初始化类数据。

我们可以添加一个构造函数来为用户提供名称和薪水,如下所示 -

public class User{

   private string name;

   private int salary;

   public User(string name, int salary){

     this.name= name;

     this.salary= salary;

   }

   public void Promote(){

      salary += 1000;

   }

}

拥有构造函数允许我们在创建新实例时传递用户的姓名和薪水。

var alice = new User("Alice", 50000);

var bob = new User("Bob", 45000);

一个类中可能有多个构造函数。拥有多个构造函数允许我们以不同的方式初始化类。例如,我们可以添加另一个构造函数,它只接受用户名并分配默认工资。

public User(string name){

   this.name = name;

   this.salary = 50000;

}

示例

using System;

class Program{

   static void Main(){

      var alice = new User();

      alice.Print();

      var bob = new User();

      bob.Print();

      var chris = new User("Chris", 50000);

      chris.Print();

      var debs = new User("Debs", 45000);

      debs.Print();

      var scott = new User("Scott");

      scott.Print();

   }

}

public class User{

   private string name;

   private int salary;

   public User(){

   }

   public User(string name){

     this.name= name;

     this.salary= 50000;

   }

   public User(string name, int salary){

     this.name= name;

     this.salary= salary;

   }

   public void Promote(){

      salary += 1000;

   }

   public void Print(){

      Console.WriteLine($"{name}: {salary}");

   }

}

输出结果
: 0

: 0

Chris: 50000

Debs: 45000

Scott: 50000

以上是 解释C#中类的概念 的全部内容, 来源链接: utcz.com/z/331739.html

回到顶部