10

我有一个MyObject带有属性 ( ) 的对象 ( MyProperty)。我想得到它的类型名称(即StringMyClass)。我用:

PropertyInfo propInfo = typeof(MyObject).GetProperty("MyProperty");
Console.WriteLine(propInfo.PropertyType.Name);
Console.WriteLine(propInfo.PropertyType.FullName);

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

集合`1

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

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

4

3 回答 3

11

`1表示泛型类型,具有 1 个泛型参数。

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

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));
            }
        }
    }
}

另一种方法是在这里。@ 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();
}
于 2011-07-05T14:29:13.477 回答
8

这是一个 CLR 内部类型名。

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

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

于 2011-07-05T14:26:46.223 回答
0

SLaks 已经解释了 `1 的含义。

关于您的第二个问题:您可以使用Type.GetGenericArguments获取泛型类型参数的名称:

if (propInfo.PropertyType.IsGenericType) {
    Type[] typeArguments = propInfo.PropertyType.GetGenericArguments();
    // typeArguments now contains an array of types ({String} in your example).
}
于 2011-07-05T14:32:35.867 回答