加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 具有泛型属性的对象类型中的“撇号”的含义是什么(例如“C

发布时间:2020-12-15 03:46:00 所属栏目:百科 来源:网络整理
导读:我有一个对象(MyObject)与一个属性(MyProperty).我想得到它的类型名称(即String或MyClass等).我用: PropertyInfo propInfo = typeof(MyObject).GetProperty("MyProperty");Console.WriteLine(propInfo.PropertyType.Name);Console.WriteLine(propInfo.Prope
我有一个对象(MyObject)与一个属性(MyProperty).我想得到它的类型名称(即String或MyClass等).我用:
PropertyInfo propInfo = typeof(MyObject).GetProperty("MyProperty");
Console.WriteLine(propInfo.PropertyType.Name);
Console.WriteLine(propInfo.PropertyType.FullName);

简单类型没有问题,但是当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>”?

解决方法

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

另一种方法是here.
参见下面的@ 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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读