元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
C#运行时环境
▶
CLR基础架构
CLR组成与生命周期
托管代码执行流程
应用程序域机制
▶
程序集体系
程序集元数据结构
强名称与版本控制
动态程序集生成
▶
类型系统
CTS核心规范
值类型与引用类型
类型加载与验证
▶
编译与执行
▶
编译过程
从源代码到IL
JIT编译原理
AOT编译机制
▶
执行引擎
方法表结构
栈帧与调用约定
尾调用优化
▶
IL深入解析
IL指令集解析
元数据表结构
调试符号处理
▶
内存管理
▶
垃圾回收
分代回收算法
终结器机制
GC句柄类型
▶
内存模型
托管堆结构
栈内存管理
大对象堆优化
▶
内存优化
内存碎片处理
ArrayPool机制
Span内存视图
发布时间:
2025-03-24 10:19
↑
☰
# CTS核心规范 ## CTS概述 Common Type System (CTS) 是.NET平台的类型系统基础,它定义了所有.NET语言共同遵循的类型规范。CTS确保了不同.NET语言之间的互操作性,并为运行时提供了统一的类型处理机制。 ## 类型分类 ### 1. 值类型和引用类型 ```csharp // 值类型示例 public struct Point { public int X { get; set; } public int Y { get; set; } public Point(int x, int y) { X = x; Y = y; } } // 引用类型示例 public class Person { public string Name { get; set; } public int Age { get; set; } } ``` ### 2. 内置类型 ```csharp public class BuiltInTypes { public void DemonstrateTypes() { // 整数类型 sbyte int8 = 127; // 8位有符号整数 byte uint8 = 255; // 8位无符号整数 short int16 = 32767; // 16位有符号整数 ushort uint16 = 65535; // 16位无符号整数 int int32 = 2147483647; // 32位有符号整数 uint uint32 = 4294967295; // 32位无符号整数 long int64 = 9223372036854775807; // 64位有符号整数 ulong uint64 = 18446744073709551615; // 64位无符号整数 // 浮点类型 float float32 = 3.14159f; // 32位浮点数 double float64 = 3.14159; // 64位浮点数 decimal decimal128 = 3.14159m; // 128位十进制数 // 其他基本类型 char character = 'A'; // 16位Unicode字符 bool boolean = true; // 布尔值 string text = "Hello"; // 字符串 object obj = null; // 对象引用 } } ``` ## 类型成员 ### 1. 字段和属性 ```csharp public class TypeMembers { // 字段 private readonly int id; private string name; // 自动属性 public int Age { get; set; } // 带有后备字段的属性 private string _email; public string Email { get { return _email; } set { if (value.Contains("@")) { _email = value; } } } // 计算属性 public bool IsAdult { get { return Age >= 18; } } } ``` ### 2. 方法和构造器 ```csharp public class MethodExample { // 实例构造器 public MethodExample() { // 默认构造 } // 带参数的构造器 public MethodExample(string name) { this.Name = name; } // 实例方法 public void DoWork() { // 方法实现 } // 静态方法 public static MethodExample Create(string name) { return new MethodExample(name); } // 虚方法 public virtual void Process() { // 基类实现 } // 属性 public string Name { get; set; } } ``` ## 类型继承和实现 ### 1. 类继承 ```csharp // 基类 public abstract class Animal { public string Name { get; set; } public abstract void MakeSound(); public virtual void Move() { Console.WriteLine($"{Name} is moving"); } } // 派生类 public class Dog : Animal { public override void MakeSound() { Console.WriteLine("Woof!"); } public override void Move() { base.Move(); Console.WriteLine("on four legs"); } } ``` ### 2. 接口实现 ```csharp // 接口定义 public interface ILogger { void Log(string message); bool IsEnabled { get; } } // 接口实现 public class ConsoleLogger : ILogger { public bool IsEnabled { get; set; } = true; public void Log(string message) { if (IsEnabled) { Console.WriteLine($"[{DateTime.Now}] {message}"); } } } ``` ## 泛型类型 ### 1. 泛型类 ```csharp public class Container<T> { private T[] items; private int count; public Container(int capacity) { items = new T[capacity]; } public void Add(T item) { if (count < items.Length) { items[count++] = item; } } public T GetItem(int index) { if (index < count) { return items[index]; } throw new IndexOutOfRangeException(); } } ``` ### 2. 泛型约束 ```csharp // 定义一个基础接口 public interface IEntity { int Id { get; set; } } // 使用泛型约束 public class Repository<T> where T : class, IEntity, new() { private List<T> items = new List<T>(); public void Add(T item) { items.Add(item); } public T GetById(int id) { return items.FirstOrDefault(x => x.Id == id); } public T CreateNew() { return new T(); } } ``` ## 类型安全 ### 1. 类型检查 ```csharp public class TypeSafety { public void DemonstrateTypeSafety() { // 编译时类型检查 string text = "Hello"; // text = 42; // 编译错误 // 运行时类型检查 object obj = "World"; if (obj is string) { string str = obj as string; Console.WriteLine(str.Length); } // 模式匹配 if (obj is string s) { Console.WriteLine(s.Length); } } } ``` ### 2. 类型转换 ```csharp public class TypeConversion { public void DemonstrateConversion() { // 隐式转换 int number = 42; long bigNumber = number; // int到long的隐式转换 // 显式转换 double pi = 3.14159; int roundedPi = (int)pi; // 需要显式转换 // 安全转换 string numberText = "123"; if (int.TryParse(numberText, out int result)) { Console.WriteLine($"转换成功: {result}"); } } } ``` ## 最佳实践 ### 1. 类型设计原则 ```csharp // 遵循单一职责原则 public class UserManager { private readonly ILogger logger; private readonly IUserRepository repository; public UserManager(ILogger logger, IUserRepository repository) { this.logger = logger; this.repository = repository; } public async Task<bool> CreateUser(User user) { try { await repository.Add(user); logger.Log($"Created user: {user.Name}"); return true; } catch (Exception ex) { logger.Log($"Error creating user: {ex.Message}"); return false; } } } ``` ### 2. 类型安全性保证 ```csharp public class SafetyPractices { // 使用不可变类型 public readonly struct Point { public readonly int X { get; } public readonly int Y { get; } public Point(int x, int y) { X = x; Y = y; } } // 防御性编程 public class SafeList<T> { private readonly List<T> items = new List<T>(); public void Add(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } items.Add(item); } public IReadOnlyList<T> GetItems() { return items.AsReadOnly(); } } } ``` ## 总结 CTS是.NET平台的核心基础之一,它定义了类型系统的基本规则和行为。通过理解和正确使用CTS,我们可以: 1. 编写类型安全的代码 2. 实现跨语言互操作 3. 创建可重用的组件 4. 提高代码的可维护性 在实际开发中,应该遵循CTS的规范,合理使用类型系统的特性,同时注意类型安全和性能优化。