获取用户友好的名称为泛型类型在C# [英] Get user-friendly name for generic type in C#

查看:260
本文介绍了获取用户友好的名称为泛型类型在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有写一个递归方法,这将给一个'用户友好'的名称泛型类型从键入类?

一个简单的方法

例如。对于以下code我想是这样的名单,其中,字典<诚信>>而不是由以下code给出的缩写或全名:

  VAR列表=新的名单,其中,字典< INT,字符串>>();
VAR类型= list.GetType();

Console.WriteLine(type.Name);
Console.WriteLine(type.FullName);
 

解决方案

根据您编辑的问题,你想是这样的:

 公共静态字符串GetFriendlyName(这种类型)
{
    如果(类型== typeof运算(INT))
        返回INT;
    否则,如果(类型== typeof运算(短))
        返回短;
    否则,如果(类型== typeof运算(字节))
        返回字节;
    否则,如果(类型== typeof运算(布尔))
        返回布尔;
    否则,如果(类型== typeof运算(长))
        回到长;
    否则,如果(类型== typeof运算(浮点))
        返回浮动;
    否则,如果(类型== typeof运算(双))
        返回双规;
    否则,如果(类型== typeof运算(十进制))
        返回十进制;
    否则,如果(类型== typeof运算(字符串))
        返回字符串;
    否则,如果(type.IsGenericType)
        返回type.Name.Split(''')[0] +&其中; +的string.join(,,type.GetGenericArguments()选择(X => GetFriendlyName(X))的ToArray()。)+>中;
    其他
        返回type.Name;
}
 

Is there an easy way without writing a recursive method which will give a 'user friendly' name for a generic type from the Type class?

E.g. For the following code I want something like 'List<Dictionary<Int>>' instead of the shorthand or full name given by the following code:

var list = new List<Dictionary<int, string>>();
var type = list.GetType();

Console.WriteLine(type.Name);
Console.WriteLine(type.FullName);

解决方案

Based on your edited question, you want something like this:

public static string GetFriendlyName(this Type type)
{
    if (type == typeof(int))
        return "int";
    else if (type == typeof(short))
        return "short";
    else if (type == typeof(byte))
        return "byte";
    else if (type == typeof(bool)) 
        return "bool";
    else if (type == typeof(long))
        return "long";
    else if (type == typeof(float))
        return "float";
    else if (type == typeof(double))
        return "double";
    else if (type == typeof(decimal))
        return "decimal";
    else if (type == typeof(string))
        return "string";
    else if (type.IsGenericType)
        return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x)).ToArray()) + ">";
    else
        return type.Name;
}

这篇关于获取用户友好的名称为泛型类型在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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