Get the type name

后端 未结 10 844
星月不相逢
星月不相逢 2020-12-05 23:05

How i can get full right name of generic type?

For example: This code

typeof(List).Name

return

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 23:51

    Use the FullName property.

    typeof(List).FullName
    

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

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

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

    typeof( List ) )
    typeof( List> )
    

    It returns:

    List
    List>
    

    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.

提交回复
热议问题