Inside C#(一些内部实现的东西)
You write:
public enum Compression {
Zip, SuperZip, None
}
The C# compiler generates:
public struct Compression : Enum {
public int value__;
public const Compression Zip = 0;
public const Compression SuperZip = 1;
public const Compression None = 2;
}
What can we learn:
1)Enums 是struct ,内部成员即是struct 也是Enum 。
2)Enum 继承System.Enum 的,structs可以继承ValueType,也可以是Enum 。
3)Enum 内部成员默认是Int的。
4)变量含有”__“的不能使用。
5)所有的值都是const 的,因此在没有重新编译的时候是不能改变的,而且也是类型安全的。
You write:
public class Resource
{
~Resource() {
...
}
}
The C# compiler generates:
public class Resource
{
protected override void Finalize() {
try {
...
}
finally {
base.Finalize();
}
}
}
What can we learn:
1)解析函数是重写基类的finalize 的。且是不确定的。
2)method (represented by the “…”)是放在Try里,无论有没有异常都会调用基类的finalize 。
You write:
using (Resource res = new Resource()) {
res.DoWork();
}
The C# compiler generates:
Resource res = new Resource(...);
try {
res.DoWork();
}
finally {
if (res != null)
((IDisposable)res).Dispose();
}
What can we learn:
使用using 会被编译成try,且会始终执行Dispose方法(基于CLR的异常)。
You write:
object x = ... ;
lock (x) {
// critical section
}
The C# compiler generates:
System.Threading.Monitor.Enter(x);
try {
// critical section
}
finally {
System.Threading.Monitor.Exit(x);
}
What can we learn:
1) Lock just uses Monitor.Enter and Exit… reading those docs give you a good idea of what is really happening here.
2) We see our friend try..finally again. This time ensuring that the monitor is exited even if an exception is thrown in the critical section
You write:
ArrayList list = new ArrayList();
foreach(int x in list) { // do nothing }
The C# compiler generates:
ArrayList list1;
int num1;
IEnumerator enumerator1;
IDisposable disposable1;
list1 = new ArrayList();
enumerator1 = list1.GetEnumerator();
try {
while (enumerator1.MoveNext()) {
num1 = ((int) enumerator1.Current);
}
return;
}
finally {
disposable1 = (enumerator1 as IDisposable);
if (disposable1 != null) {
disposable1.Dispose();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述