C# 类(Class)
系统讲解 C# 类的定义蓝图与默认访问修饰符、点运算符成员访问、私有字段封装、默认与参数化构造函数、析构函数(终结器)与 CLR 垃圾回收机制,以及 static 静态字段与静态方法,并在本地 csc4 实测验证。
学完这一章,你能够
- 系统讲解 C# 类的定义蓝图与默认访问修饰符、点运算符成员访问、私有字段封装、默认与参数化构造函数、析构函数(终结器)与 CLR 垃圾回收机制,以及 static 静态字段与静态方法,并在本地 csc4 实测验证。
类的定义语法、默认可见性与点运算符访问
在面向对象设计中,类(`class`)定义了数据类型的蓝图:它本身不占据具体业务数据,而是规定由该蓝图实例化出的对象(Object)拥有哪些字段成员与行为方法。类定义以可选访问修饰符加 `class` 关键字和类名开头,主体由花括号包裹。需要注意:顶级类的默认访问修饰符为 `internal`(同程序集可见),类内部成员的默认访问修饰符为 `private`;外部通过对象名配合点运算符(`.`)即可链接并访问可及成员。
声明 `Box` 类并用 `new Box()` 创建 `Box1` 与 `Box2` 两个独立对象后,通过点运算符分别设置二者的长、宽、高并计算体积:本站实测 `6*7*5` 得 `210`、`12*13*10` 得 `1560`。
成员函数与私有字段封装
成员函数定义在类体内,可直接访问当前对象的所有字段(含私有成员)。遵循封装设计原则,通常应将 `length`、`breadth`、`height` 等核心状态字段声明为 `private` 以防外部随意篡改,再对外暴露 `SetLength`、`SetBreadth`、`SetHeight` 与 `GetVolume` 等公有方法统一读写。本站实测封装版 `EncapsulatedBox` 同样精确算出两个盒子的体积 `210` 与 `1560`。
构造函数与析构函数(终结器)
构造函数(Constructor)是与类完全同名且没有任何返回类型(连 `void` 也不写)的特殊成员函数,在 `new` 创建对象时自动执行。未带参数的称为默认/无参构造函数;带有参数的称为参数化构造函数,可在实例化瞬间为字段赋予初值(注意:一旦显式定义了参数化构造函数,编译器将不再自动补发隐式无参构造函数,如需两者并存须同时显式写出)。本站实测 `new Line()` 与 `new Line(10.0)` 分别触发对应构造路径并完成长度读写。
析构函数(在 .NET 中正式称为终结器 Finalizer)以波浪号前缀 `~ClassName()` 声明,无访问修饰符、无返回值、无参数,且不可被继承或重载,用于在对象被垃圾回收器(GC)回收前释放非托管资源。需准确理解 CLR 运行机制:与 C++ 离开作用域立即析构不同,C# 终结器由 GC 在非确定时刻触发执行,工程上需要确定性释放文件句柄或网络连接时应实现 `IDisposable` 并配合 `using` 语句。本站通过独立无内联作用域创建短生命周期对象并显式触发 `GC.Collect()` 与 `GC.WaitForPendingFinalizers()`,实测确认 `~TrackedFinalizer()` 被 CLR 终结器线程准确调用 1 次。
类的静态成员:static 字段与 static 方法
使用 `static` 修饰的成员隶属于类本身而非单个实例:无论创建多少个对象,静态字段在类型加载域中都仅存在唯一一份共享副本(可在类内声明处初始化,也可通过静态构造函数或外部赋值)。本站实测通过两个独立实例 `s1`、`s2` 各调用 3 次 `Count()` 后,二者读取共享静态字段 `num` 均观测到 `6`。
将方法声明为 `static` 后,该方法在任何对象实例化之前就已存在,可直接通过 `类名.方法名()`(如 `StaticVar.GetNum()`)调用;由于不绑定具体对象实例,静态方法内部不能直接访问非静态实例成员,只能访问静态成员或接收传入参数。本站实测三次累加后直接调用 `StaticVar.GetNum()` 返回 `3`,继续累加后返回 `6`。
在本地 csc4 实测类实例化与封装、无参/有参构造、GC 终结器及 static 共享成员
展开查看收起
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
namespace CSharpClassLab
{
internal class PublicBox
{
public double length;
public double breadth;
public double height;
}
internal class EncapsulatedBox
{
private double length;
private double breadth;
private double height;
public void SetLength(double len) { length = len; }
public void SetBreadth(double bre) { breadth = bre; }
public void SetHeight(double hei) { height = hei; }
public double GetVolume() { return length * breadth * height; }
}
internal class Line
{
private double length;
public static List<string> Events = new List<string>();
public Line()
{
Events.Add("ctor:default");
}
public Line(double len)
{
length = len;
Events.Add(string.Format(CultureInfo.InvariantCulture, "ctor:{0}", len));
}
public void SetLength(double len) { length = len; }
public double GetLength() { return length; }
}
internal class TrackedFinalizer
{
public static int FinalizedCount = 0;
~TrackedFinalizer()
{
FinalizedCount++;
}
}
internal class StaticVar
{
public static int num;
public void Count()
{
num++;
}
public int GetInstanceView()
{
return num;
}
public static int GetNum()
{
return num;
}
}
internal class Program
{
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CreateShortLivedFinalizable()
{
TrackedFinalizer temp = new TrackedFinalizer();
if (temp == null)
{
throw new InvalidOperationException();
}
}
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
private static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: Class definition & dot operator access
PublicBox b1 = new PublicBox();
b1.height = 5.0; b1.length = 6.0; b1.breadth = 7.0;
PublicBox b2 = new PublicBox();
b2.height = 10.0; b2.length = 12.0; b2.breadth = 13.0;
double v1 = b1.height * b1.length * b1.breadth;
double v2 = b2.height * b2.length * b2.breadth;
string actual1 = string.Format(CultureInfo.InvariantCulture, "v1={0},v2={1}", v1, v2);
cases.Add(CaseJson(
"class_definition_and_dot_access",
"验证 Box 类实例化与点运算符读写公有字段并计算两个盒子体积",
"v1=210,v2=1560",
actual1
));
// Case 2: Encapsulation with private fields and public methods
EncapsulatedBox eb1 = new EncapsulatedBox();
eb1.SetLength(6.0); eb1.SetBreadth(7.0); eb1.SetHeight(5.0);
EncapsulatedBox eb2 = new EncapsulatedBox();
eb2.SetLength(12.0); eb2.SetBreadth(13.0); eb2.SetHeight(10.0);
string actual2 = string.Format(
CultureInfo.InvariantCulture,
"eb1={0},eb2={1}",
eb1.GetVolume(), eb2.GetVolume()
);
cases.Add(CaseJson(
"class_encapsulation_methods",
"验证将字段设为 private 并通过公有 Set/Get 方法封装对象状态",
"eb1=210,eb2=1560",
actual2
));
// Case 3: Default constructor & parameterized constructor
Line.Events.Clear();
Line l1 = new Line();
l1.SetLength(6.0);
Line l2 = new Line(10.0);
double initL2 = l2.GetLength();
l2.SetLength(6.0);
string actual3 = string.Format(
CultureInfo.InvariantCulture,
"events={0},l1={1},l2init={2},l2after={3}",
string.Join("|", Line.Events.ToArray()), l1.GetLength(), initL2, l2.GetLength()
);
cases.Add(CaseJson(
"constructors_default_and_parameterized",
"验证无参构造函数与参数化构造函数在对象实例化时的执行与初始值设定",
"events=ctor:default|ctor:10,l1=6,l2init=10,l2after=6",
actual3
));
// Case 4: Destructor / Finalizer (~ClassName) invoked via GC
TrackedFinalizer.FinalizedCount = 0;
CreateShortLivedFinalizable();
GC.Collect();
GC.WaitForPendingFinalizers();
string actual4 = string.Format("finalized={0}", TrackedFinalizer.FinalizedCount);
cases.Add(CaseJson(
"destructor_finalizer_gc",
"验证无参无返回析构函数(终结器 ~TrackedFinalizer)在对象不可达并触发 GC 终结队列后执行",
"finalized=1",
actual4
));
// Case 5: Static fields shared across instances & static methods
StaticVar.num = 0;
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.Count(); s1.Count(); s1.Count();
int afterS1 = StaticVar.GetNum();
s2.Count(); s2.Count(); s2.Count();
string actual5 = string.Format(
"afterS1={0},s1View={1},s2View={2},staticCall={3}",
afterS1, s1.GetInstanceView(), s2.GetInstanceView(), StaticVar.GetNum()
);
cases.Add(CaseJson(
"static_fields_and_methods",
"验证 static 字段在多实例间共享单一副本以及通过类名直接调用静态方法",
"afterS1=3,s1View=6,s2View=6,staticCall=6",
actual5
));
Console.WriteLine(string.Format(
"{{\"version\":{0},\"cases\":[{1}]}}",
Esc("CLR " + Environment.Version.ToString()),
string.Join(",", cases.ToArray())
));
}
}
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
会导致编译错误。因为只要类显式声明了任意构造函数,C# 编译器便不再自动生成默认无参构造函数;若仍需支持无参实例化,必须手动补写无参构造函数或为参数提供默认值。