C#学习 [类型系统] 类(13)
概念
定义为 class 的类型是引用类型。 在运行时,如果声明引用类型的变量,此变量就会一直包含值 null,直到使用 new 运算符显式创建类实例,或直到为此变量分配已在其他位置创建的兼容类型。
//Declaring an object of type MyClass.
MyClass mc = new MyClass();
//Declaring another object of the same type, assigning it the value of the first object.
MyClass mc2 = mc;
声明
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}
创建
Customer object1 = new Customer();
Customer object2;
Customer object3 = new Customer();
Customer object4 = object3;
构造函数和初始化
创建类型的实例时,需要确保其字段和属性已初始化为有用的值。 可通过多种方式初始化值:
- 接受默认值
- 字段初始化表达式
- 构造函数参数
- 对象初始值设定项
public class Container
{
// Initialize capacity field to a default value of 10:
private int _capacity = 10;
}
public class Container
{
private int _capacity;
public Container(int capacity) => _capacity = capacity;
}
从 C# 12 开始,可以将主构造函数定义为类声明的一部分:
public class Container(int capacity)
{
private int _capacity = capacity;
}
public class Person
{
public required string LastName { get; set; }
public required string FirstName { get; set; }
}
添加 required 关键字要求调用方必须将这些属性设置为 new 表达式的一部分:
var p1 = new Person(); // 编译发生错误!!!
var p2 = new Person() { FirstName = "Grace", LastName = "Hopper" };
继承
类完全支持继承,创建类时,可以从其他任何未定义为 sealed 的类继承。 其他类可以从你的类继承并替代类虚拟方法。
类可以实现一个或多个接口。
public class Manager : Employee
{
// Employee fields, properties, methods and events are inherited
// New Manager fields, properties, methods and events go here...
}
本文来自博客园,作者:huiy_小溪,转载请注明原文链接:https://www.cnblogs.com/huiy/p/18511211