基本类型
本文档介绍 Roslyn 中的基本类型,包括值类型、引用类型和内置类型。
📋 文档信息
| 属性 | 值 |
|---|---|
| 难度 | 中级 |
| 阅读时间 | 25 分钟 |
| 前置知识 | C# 类型系统基础 |
| 相关文档 | 类型系统索引、语义模型 API |
值类型和引用类型
检查类型种类
csharp
public bool IsValueType(ITypeSymbol type)
{
return type.IsValueType;
}
public bool IsReferenceType(ITypeSymbol type)
{
return type.IsReferenceType;
}类型种类枚举
csharp
public string GetTypeKindDescription(ITypeSymbol type)
{
return type.TypeKind switch
{
TypeKind.Class => "类",
TypeKind.Struct => "结构",
TypeKind.Interface => "接口",
TypeKind.Enum => "枚举",
TypeKind.Delegate => "委托",
TypeKind.Array => "数组",
_ => "其他"
};
}内置类型
特殊类型
csharp
public bool IsSpecialType(ITypeSymbol type, SpecialType specialType)
{
return type.SpecialType == specialType;
}
// 常用特殊类型
// SpecialType.System_Object
// SpecialType.System_String
// SpecialType.System_Int32
// SpecialType.System_Boolean可空类型
检查可空性
csharp
public bool IsNullable(ITypeSymbol type)
{
return type.NullableAnnotation == NullableAnnotation.Annotated;
}
public ITypeSymbol GetUnderlyingType(ITypeSymbol type)
{
if (type is INamedTypeSymbol namedType &&
namedType.IsGenericType &&
namedType.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T)
{
return namedType.TypeArguments[0];
}
return type;
}关键要点
- ✅ 使用
IsValueType和IsReferenceType区分类型 - ✅ 使用
TypeKind枚举识别具体类型种类 - ✅ 使用
SpecialType识别内置类型 - ✅ 使用
NullableAnnotation检查可空性
相关文档
最后更新: 2026-02-06