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

动态代码生成场景下,如何将Type转为C#可解析字符串?

Type实例转合法C#代码字符串的现成方案

.NET 内置工具

1. System.CodeDom.CodeTypeReference

直接用CodeTypeReference类就能自动处理泛型、可空类型的语法转换,输出符合C#规范的类型字符串:

using System.CodeDom;

public static string GetValidCSharpTypeName(Type type)
{
    var typeReference = new CodeTypeReference(type);
    return typeReference.BaseType;
}

它会把System.Collections.Generic.List1[System.String]转为System.Collections.Generic.List<System.String>,把System.Nullable1[System.Int32]转为System.Nullable<System.Int32>。如果需要简化命名(比如List<string>),可以在生成代码时添加对应的using指令导入命名空间。

2. .NET 6+ 结合命名空间简化

如果要输出更简洁的类型名(如List<string>而非全限定名),可以基于CodeTypeReference的结果,配合提前收集的命名空间列表做前缀替换,进一步简化输出。

开源库方案

1. Roslyn(.NET Compiler Platform)

利用Microsoft.CodeAnalysis.CSharp的API可以高度自定义类型格式,支持简化命名、可空类型友好显示等:

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

public static string GetCSharpTypeName(Type type)
{
    var compilation = CSharpCompilation.Create("TempCompilation");
    var typeSymbol = compilation.GetTypeByMetadataName(type.FullName);
    if (typeSymbol == null) return type.ToString();
    
    var displayFormat = new SymbolDisplayFormat(
        typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
        genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
        nullableReferenceTypeStyle: SymbolDisplayNullableReferenceTypeStyle.Name
    );
    return SymbolDisplay.FormatType(typeSymbol, displayFormat);
}

这个方法可以灵活控制输出,比如直接生成List<string>或int?这类简洁格式。

2. Humanizer

通过Humanizer库的扩展方法可以快速实现类型的友好转换,安装NuGet包Humanizer后使用:

using Humanizer;

public static string GetCSharpTypeName(Type type)
{
    return type.Humanize();
}

它会自动将泛型、可空类型转为符合C#习惯的字符串,比如把Nullable<int>对应的Type实例转成int?。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 07:02:06