具有泛型的属性的对象类型(例如"Collection`1")中"撇号+数字"的含义是什么?

blu*_*ish 10 .net c# generics reflection fully-qualified-naming

我有一个MyObject带有property(MyProperty)的object ().我想要得到它的类型名称(即StringMyClass等).我用:

PropertyInfo propInfo = typeof(MyObject).GetProperty("MyProperty");
Console.WriteLine(propInfo.PropertyType.Name);
Console.WriteLine(propInfo.PropertyType.FullName);
Run Code Online (Sandbox Code Playgroud)

简单类型没有问题,但是当MyProperty它是泛型类型时,我在获取它的名字方面遇到了问题(例如Collection<String>).它打印:

Collection`1

System.Collections.ObjectModel.Collection`1 [[System.String,mscorlib,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]

那是什么`1?我怎样才能获得" Collection<String>"?

Geo*_*ett 11

"1"表示泛型类型,带有1个通用参数.

获取字符串的一种方法是使用System.CodeDom,如@LukeH所示:

using System;
using System.CodeDom;
using System.Collections.Generic;
using Microsoft.CSharp;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var p = new CSharpCodeProvider())
            {
                var r = new CodeTypeReference(typeof(Dictionary<string, int>));

                Console.WriteLine(p.GetTypeOutput(r));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法就在这里.请参阅下面的@ jaredpar代码:

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();
}
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 8

这是CLR内部类型名称.

该数字是泛型类型参数的数量,因为类型可以重载.
(Func`1并且Func`2是不同的类型)

由于CLR与C#无关,因此没有内置方法来获取C#样式的类型名称.

  • 你可以使用CodeDom实际获得C#风格的名字,但我可能不会打扰!像`using(var p = new CSharpCodeProvider()){var r = new CodeTypeReference(propInfo.PropertyType); Console.WriteLine(p.GetTypeOutput(R)); }` (5认同)
  • @LukeH,我认为评论应该是一个答案. (3认同)