【问题标题】:Language-agnostic way of displaying the generic types along with their type arguments?显示泛型类型及其类型参数的与语言无关的方式?
【发布时间】:2015-05-26 06:57:44
【问题描述】:

假设我想记录/显示这种类型的名称:

Dictionary<string, Dictionary<Guid, DateTime>>

什么是首选:

1) 字典`2`string`Dictionary`2`Guid`DateTime

2) Dictionary`2(string, Dictionary`2(Guid, DateTime))

3) 字典>

JVM 是如何解决这个问题的?

另见:https://stackoverflow.com/a/2448918/486561

【问题讨论】:

    标签: .net string reflection types language-agnostic


    【解决方案1】:

    有点长,但typeof(Dictionary&lt;string, Dictionary&lt;Guid, DateTime&gt;&gt;).FullName 是:

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

    typeof() 运算符返回一个RuntimeType,它是一个 .NET 类。所以FullName 是一种.NET 类型的属性,所以它是官方的:-)

    如果您尝试执行Type.GetType(thatstring),您将获得正确的类型:-)

    可以通过typeof(Dictionary&lt;string, Dictionary&lt;Guid, DateTime&gt;&gt;).ToString() 获得更紧凑的版本,没有程序集短名称。这也可以与Type.GetType(...)一起使用

    System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.Guid,System.DateTime]]
    

    请注意,Type.GetType 存在以下格式的限制:

    要获取的类型的程序集限定名称。请参阅 AssemblyQualifiedName。 如果类型在当前执行的程序集中或在 Mscorlib.dll 中,则提供由其命名空间限定的类型名称就足够了。

    如果你有兴趣,这里有完整格式: AssemblyQualifiedName

    【讨论】:

    • 对不起,我从未提及,但我想要一个“友好”的名字:)。如果我只是去掉全部资格,你怎么看:Dictionary`2[String,Dictionary`2[Guid,DateTime]]
    • @Den 我认为命名空间仍然很重要 :-)
    • 没错,但是当您执行 typeof(...).Name 时,您不会获得命名空间。我想要两全其美:)。它更多地用于记录,而不是动态实例化。
    • @Den 现在,如果你想明确地描述一个类型,命名空间和程序集名称是必要的。如果你想给出一个“总体思路”,那么你当然可以剥离它们。也许使用正则表达式。
    • 谢谢,顺便说一句。一个非常快速、直接和彻底的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多