什么是对&QUOT的意思;撇号+电话号码和QUOT;在性能与仿制药的对象类型(例如:"。Collection`1")? [英] What's the meaning of "apostrophe + number" in the object type of properties with generics (eg. "Collection`1")?

查看:162
本文介绍了什么是对&QUOT的意思;撇号+电话号码和QUOT;在性能与仿制药的对象类型(例如:"。Collection`1")?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象(为MyObject )与属性( myProperty的)。我想获得它的类型名称(即字符串 MyClass的等)。我使用的:

I have an object (MyObject) with a property (MyProperty). I want to get it's type name (i.e. String or MyClass etc.). I use:

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

没有问题,简单的类型,但是当 myProperty的是一个泛型类型,我面临越来越问题,它的名字(比如收藏<字符串> )。它打印:

No problem with simple types, but when MyProperty is a generic type, I face problems on getting it's name (e.g. Collection<String>). It prints:

Col​​lection`1

Collection`1

System.Collections.ObjectModel.Collection`1 [System.String,mscorlib程序,版本= 2.0.0.0,文化=中性公钥= b77a5c561934e089]]

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

什么是`1 ?我怎样才能获得收藏&LT;字符串&GT;

What is that `1? And how can I obtain "Collection<String>"?

推荐答案

`1 表示泛型类型,与1泛型参数。

The `1 means a generic type, with 1 generic parameter.

获取字符串的一种方法是使用系统。codeDOM ,所建议的 @LukeH

One way of getting the string is by using the System.CodeDom, as suggested by @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));
            }
        }
    }
}

这是另一种方法是<一个href="http://stackoverflow.com/questions/401681/how-can-i-get-the-correct-text-definition-of-a-generic-type-using-reflection">here. 为@ jaredpar 的code见下:

An alternative method is here. See below for @jaredpar's code:

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

这篇关于什么是对&QUOT的意思;撇号+电话号码和QUOT;在性能与仿制药的对象类型(例如:&QUOT;。Collection`1&QUOT;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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