获取类型名称 [英] Get the type name

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

问题描述

我怎样才能获得通用型的全姓名权

How i can get full right name of generic type?

例如:
这段代码

For example: This code

typeof(List<string>).Name

。返回

List`1

代替的

List<string>



如何获得一个正确的名称?



How to get a right name?

typeof(List<string>).ToString()

返回System.Collections.Generic.List`1 [System.String],但我想获得初始名称:

returns System.Collections.Generic.List`1[System.String] but i want to get initial name:

List<string>



是真的吗?

Is it real?

推荐答案

使用 FullName属性

typeof(List<string>).FullName

$ b。
$ b

这会给你的命名空间+类+类型参数。

That will give you the namespace + class + type parameters.

你所要求的是C#特定的语法。至于.NET而言,这是正确的:

What you are asking for is a C# specific syntax. As far as .NET is concerned, this is proper:

System.Collections.Generic.List`1[System.String]

因此,为了得到你想要的,你必须写打造它,你的方式功能想要它。也许像这样:

So to get what you want, you'd have to write a function to build it the way you want it. Perhaps like so:

static string GetCSharpRepresentation( Type t, bool trimArgCount ) {
    if( t.IsGenericType ) {
        var genericArgs = t.GetGenericArguments().ToList();

        return GetCSharpRepresentation( t, trimArgCount, genericArgs );
    }

    return t.Name;
}

static string GetCSharpRepresentation( Type t, bool trimArgCount, List<Type> availableArguments ) {
    if( t.IsGenericType ) {
        string value = t.Name;
        if( trimArgCount && value.IndexOf("`") > -1 ) {
            value = value.Substring( 0, value.IndexOf( "`" ) );
        }

        if( t.DeclaringType != null ) {
            // This is a nested type, build the nesting type first
            value = GetCSharpRepresentation( t.DeclaringType, trimArgCount, availableArguments ) + "+" + value;
        }

        // Build the type arguments (if any)
        string argString = "";
        var thisTypeArgs = t.GetGenericArguments();
        for( int i = 0; i < thisTypeArgs.Length && availableArguments.Count > 0; i++ ) {
            if( i != 0 ) argString += ", ";

            argString += GetCSharpRepresentation( availableArguments[0], trimArgCount );
            availableArguments.RemoveAt( 0 );
        }

        // If there are type arguments, add them with < >
        if( argString.Length > 0 ) {
            value += "<" + argString + ">";
        }

        return value;
    }

    return t.Name;
}

有关这些类型(与作为第二参数是true):

For these types (with true as 2nd param):

typeof( List<string> ) )
typeof( List<Dictionary<int, string>> )

它返回:

List<String>
List<Dictionary<Int32, String>>

在一般虽然,我敢打赌,你可能不的需求的有你的代码的C#表示,也许如果你这样做,有的格式比C#语法更好更合适。

In general though, I'd bet you probably don't need to have the C# representation of your code and perhaps if you do, some format better than the C# syntax would be more appropriate.

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

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