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>).它打印: 
 那是什么`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. 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();
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
