上使用反射C#获取GenericType-名称在良好的格式 [英] Get GenericType-Name in good format using Reflection on C#

查看:468
本文介绍了上使用反射C#获取GenericType-名称在良好的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在它在code声明的形式通用型的名称。

I need to get the name of generic-type in form of its declaration in code.

例如: 对于名单,其中,的Int32>我想获得字符串名单,其中,的Int32>中。 非标准性Type.Name在这种情况下返回List`1。

For example: For List<Int32> I want to get string "List<Int32>". Standart property Type.Name returns "List`1" in this situation.

编辑:例如固定

推荐答案

好吧,我已经做了一大堆的研究,发现的typeof(名单)具有GetGenericArguments,这将让你的子名称。所以我会做这种方式(1泛型类型,如果它是一个多它会采取一个循环什么的。我可以发布一个功能,如果提出要求。

Ok, I've done a bunch of research, and discovered that typeof(List) has "GetGenericArguments" which will get you the sub names. So I'd do it this way (for 1 generic type, if it is a multi it'll take a loop or something. I can post a function for that if requested.

下面是一个函数与多个通用参数,手柄嵌套泛型类型做到这一点。再次编辑,使这个应用聚合函数:

Here is a function to do it with multiple generic arguments, handles 'nested' generic types. Edited again to make this use the Aggregate function:

static string GetFullName(Type t)
{
    if (!t.IsGenericType)
        return t.Name;
    StringBuilder sb=new StringBuilder();

    sb.Append(t.Name.Substring(0, t.Name.LastIndexOf("`")));
    sb.Append(t.GetGenericArguments().Aggregate("<",

        delegate(string aggregate,Type type)
            {
                return aggregate + (aggregate == "<" ? "" : ",") + GetFullName(type);
            }  
        ));
    sb.Append(">");

    return sb.ToString();
}

这篇关于上使用反射C#获取GenericType-名称在良好的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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