Skip to content

基本类型

本文档介绍 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;
}

关键要点

  • ✅ 使用 IsValueTypeIsReferenceType 区分类型
  • ✅ 使用 TypeKind 枚举识别具体类型种类
  • ✅ 使用 SpecialType 识别内置类型
  • ✅ 使用 NullableAnnotation 检查可空性

相关文档


最后更新: 2026-02-06

基于 MIT 许可发布