ソースコード
using System;
using System.Linq;
namespace Kogane
{
public static class TypeUtils
{
public static string GetPrettyName( Type type )
{
if ( type.IsArray )
{
return $"{GetPrettyName( type.GetElementType() )}[]";
}
if ( type.IsGenericType )
{
var typeName = type.Name;
var simpleTypeName = typeName.Substring( 0, typeName.LastIndexOf( "`", StringComparison.InvariantCulture ) );
var genericArgumentsNames = string.Join( ", ", type.GetGenericArguments().Select( x => GetPrettyName( x ) ) );
return $"{simpleTypeName}<{genericArgumentsNames}>";
}
return GetCSharpTypeKeyword( type );
}
public static string GetCSharpTypeKeyword( Type type )
{
return GetCSharpTypeKeyword( type.Name );
}
public static string GetCSharpTypeKeyword( string typeName )
{
return typeName switch
{
"Boolean" => "bool",
"Byte" => "byte",
"SByte" => "sbyte",
"Char" => "char",
"Decimal" => "decimal",
"Double" => "double",
"Single" => "float",
"Int32" => "int",
"UInt32" => "uint",
"Int64" => "long",
"UInt64" => "ulong",
"Int16" => "short",
"UInt16" => "ushort",
"Object" => "object",
"String" => "string",
"Void" => "void",
_ => typeName,
};
}
}
}
通常
Debug.Log( typeof( List<int> ).Name );
Debug.Log( typeof( Dictionary<int, string> ).Name );
使用例
Debug.Log( TypeUtils.GetPrettyName( typeof( List<int> ) ) );
Debug.Log( TypeUtils.GetPrettyName( typeof( Dictionary<int, string> ) ) );