如何使用反射获得泛型类型的正确文本定义? [英] How can I get the correct text definition of a generic type using reflection?

查看:23
本文介绍了如何使用反射获得泛型类型的正确文本定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究代码生成,但遇到了泛型问题.这是导致我出现问题的原因的简化"版本.

I am working on code generation and ran into a snag with generics. Here is a "simplified" version of what is causing me issues.

Dictionary<string, DateTime> dictionary = new Dictionary<string, DateTime>();
string text = dictionary.GetType().FullName;

使用上面的代码片段,text 的值如下:

With the above code snippet the value of text is as follows:

 System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, 
 Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.DateTime, mscorlib, 
 Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

(为了更好的可读性添加了换行符.)

(Line breaks added for better readability.)

有没有办法在不解析上述字符串的情况下以不同的格式获取类型名称(type)?我希望 text 得到以下结果:

Is there a way to get the type name (type) in a different format without parsing the above string? I desire the following result for text:

System.Collections.Generic.Dictionary<System.String, System.DateTime>

推荐答案

在 .Net Framework 中没有获得这种表示的内置方法.即因为没有办法让它正确.有很多结构在 C# 样式语法中无法表示.例如,<>foo"在 IL 中是一个有效的类型名称,但不能在 C# 中表示.

There is no built-in way to get this representation in the .Net Framework. Namely because there is no way to get it correct. There are a good number of constructs that are not representable in C# style syntax. For instance "<>foo" is a valid type name in IL but cannot be represented in C#.

但是,如果您正在寻找一个很好的解决方案,它可以很快地手动实施.以下解决方案适用于大多数情况.它不会处理

However, if you're looking for a pretty good solution it can be hand implemented fairly quickly. The below solution will work for most situations. It will not handle

  1. 嵌套类型
  2. 非法的 C# 名称
  3. 其他几种情况

示例:

public static string GetFriendlyTypeName(Type type) {
    if (type.IsGenericParameter)
    {
        return type.Name;
    }

    if (!type.IsGenericType)
    {
        return type.FullName;
    }

    var builder = new System.Text.StringBuilder();
    var name = type.Name;
    var index = name.IndexOf("`");
    builder.AppendFormat("{0}.{1}", type.Namespace, name.Substring(0, index));
    builder.Append('<');
    var first = true;
    foreach (var arg in type.GetGenericArguments())
    {
        if (!first)
        {
            builder.Append(',');
        }
        builder.Append(GetFriendlyTypeName(arg));
        first = false;
    }
    builder.Append('>');
    return builder.ToString();
}

这篇关于如何使用反射获得泛型类型的正确文本定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆