【问题标题】:How can we get List<String> from System.Collections.Generic.List`1[System.String]? [closed]我们如何从 System.Collections.Generic.List`1[System.String] 中获取 List<String>? [关闭]
【发布时间】:2018-03-01 15:06:45
【问题描述】:

我正在使用 T4 模板生成 c# 类。我需要从另一个类 Class1 生成影子类。

在 Class1 中,我有 TypeAttribute,它可以告诉 Class1 中的属性类型是什么。

通过使用反射,我得到了TypeAttribute 中指定的类型。

我没有得到任何标准方法来获取未损坏格式的泛型类型。

我需要来自 System.Collections.Generic.List`1[System.String] 的List&lt;String&gt;

我正在为 T4Template 使用 T4Toolbox。

T4Toolbox 是否在生成 c# 代码时提供任何此类功能来处理泛型?

谢谢。

【问题讨论】:

  • 那已经是List&lt;string&gt;了,你只看到CLR使用的名字。
  • @HansPassant 他试图将Type 对象转换为在.cs 文件中复制它所需的字符串表示形式。

标签: c# generics reflection t4


【解决方案1】:

这是我最近在玩 T4 模板时拼凑的东西。

static class Exts
{
    public static string ToCSharpString(this Type type, StringBuilder sb = null)
    {
        sb = sb ?? new StringBuilder();

        if (type.IsGenericType)
        {
            sb.Append(type.Name.Split('`')[0]);
            sb.Append('<');
            bool first = true;
            foreach (var tp in type.GenericTypeArguments)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    sb.Append(", ");
                }

                sb.Append(tp.ToCSharpString());
            }
            sb.Append('>');
        }
        else if (type.IsArray)
        {
            sb.Append(type.GetElementType().ToCSharpString());
            sb.Append("[]");
        }
        else
        {
            sb.Append(type.Name);
        }

        return sb.ToString();
    }
}

可能还有更多特殊情况,但它涵盖了泛型和数组。

var list = typeof(List<string>).ToCSharpString();
// List<String>

var dict = typeof(Dictionary<int, HashSet<string>>).ToCSharpString();
// Dictionary<Int32, HashSet<String>>

var array = typeof(Dictionary<int, HashSet<string>>[]).ToCSharpString();
// Dictionary<Int32, HashSet<String>>[]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多