You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#反射如何获取List<Employee>格式类型名而非CLR内部名称?

优雅获取可编译的C#类型名称

用CSharpCodeProvider一键转换(最省心)

直接借助.NET自带的代码生成工具类,它能自动处理所有类型格式问题,不用自己写繁琐的判断逻辑:

using Microsoft.CSharp;
using System.CodeDom;

public static string GetCSharpTypeName(Type type)
{
    using var provider = new CSharpCodeProvider();
    return provider.GetTypeOutput(new CodeTypeReference(type));
}

这个方法会把List<Employee>转换成System.Collections.Generic.List<Employee>,Dictionary<string, Employee>转换成System.Collections.Generic.Dictionary<string, Employee>,完全符合编译要求,还能自动处理数组、嵌套类型等其他复杂情况。

手动递归处理(自定义度高)

如果不想依赖额外类库,自己写递归逻辑处理泛型、数组等场景也很灵活:

public static string GetFriendlyTypeName(Type type)
{
    // 处理泛型类型
    if (type.IsGenericType)
    {
        var baseTypeName = type.GetGenericTypeDefinition().Name.Split('`')[0];
        var genericArgs = string.Join(", ", type.GetGenericArguments().Select(GetFriendlyTypeName));
        return $"{type.Namespace}.{baseTypeName}<{genericArgs}>";
    }
    // 处理数组类型
    else if (type.IsArray)
    {
        return $"{GetFriendlyTypeName(type.GetElementType())}[]";
    }
    // 处理嵌套类型
    else if (type.IsNested)
    {
        return $"{GetFriendlyTypeName(type.DeclaringType)}.{type.Name}";
    }
    // 普通类型直接返回完整命名空间+类型名
    return $"{type.Namespace}.{type.Name}";
}

要是生成的代码里已经添加了using System.Collections.Generic;这类命名空间引用,直接去掉type.Namespace.部分,就能得到更简洁的类型名。

用Roslyn API(现代化方案)

针对.NET Core/.NET 5+的项目,用Roslyn的格式化工具能更贴合现代C#语法,还能处理int?这类nullable值类型的格式:

using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

public static string GetRoslynTypeName(Type type)
{
    var compilation = CSharpCompilation.Create("TempCompilation");
    var typeSymbol = compilation.GetTypeByMetadataName(type.FullName);
    var formatter = new CSharpDisplayFormatter();
    return formatter.FormatSymbol(typeSymbol, null, null);
}

内容的提问来源于stack exchange,提问作者user788454

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:45:34