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

C#中如何便捷优雅地获取带泛型的Dictionary类型名称?

更便捷优雅的C#泛型Dictionary类型名称获取方法

你当前的实现虽然可行,但可以通过以下几种更简洁优雅的方式实现需求:

方法一:基于Type.ToString()的字符串处理

利用Type.ToString()返回的类型字符串直接处理,无需手动拆分泛型参数:

var propertyType = property.PropertyType;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
    var friendlyName = propertyType.ToString()
        .Replace("System.Collections.Generic.", "") // 移除命名空间前缀
        .Replace("`2[", "<")
        .Replace("]", ">")
        .Replace(", ", ","); // 可选:移除泛型参数间的空格,保留则删除此行
    properties[property.Name] = friendlyName;
}

该方法无需额外引用,代码简洁,处理后会得到类似Dictionary<int,string>或Dictionary<int, string>的结果。

方法二:通用泛型类型名称扩展方法

如果需要处理更多泛型类型(不止Dictionary),可以封装一个通用扩展方法,复用性更强:

public static class TypeExtensions
{
    public static string GetFriendlyTypeName(this Type type)
    {
        if (!type.IsGenericType)
            return type.Name;
            
        // 获取泛型类型的基础名称(去掉`及后面的数字)
        var baseTypeName = type.GetGenericTypeDefinition().Name;
        baseTypeName = baseTypeName.Substring(0, baseTypeName.IndexOf('`'));
        
        // 拼接泛型参数名称
        var genericArgs = string.Join(", ", type.GetGenericArguments().Select(t => t.Name));
        return $"{baseTypeName}<{genericArgs}>";
    }
}

使用时只需一行代码:

if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
    properties[property.Name] = property.PropertyType.GetFriendlyTypeName();
}

此方法不仅适用于Dictionary,List<T>、HashSet<T>等泛型类型都可以直接调用。

方法三:利用CSharpCodeProvider生成标准类型名

借助.NET自带的代码生成类,自动生成符合C#语法规范的类型名称,无需手动处理字符串:

using System.CodeDom.Compiler;
using Microsoft.CSharp;

// ...

var propertyType = property.PropertyType;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
    using var provider = new CSharpCodeProvider();
    var typeReference = new CodeTypeReference(propertyType);
    properties[property.Name] = provider.GetTypeOutput(typeReference);
}

该方法会自动输出Dictionary<int, string>这类标准C#类型名,准确性最高,但需要添加System.CodeDom引用。

注意点

相比你原代码中判断Name == "Dictionary2"的方式,使用propertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>)`的判断逻辑更准确,能避免自定义泛型类名称冲突的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:22:55