Type 格式化FullName

 
由于工作原因,会写一些生成代码的工具,总是需要获取类型的FullName,在生成代码中声明类型。可是Type.FullName的格式总是很恶心。像是泛型总是会存在“`1`2”这类字符,甚至还有冗长的程序集信息,以及嵌套类”+“的符号。
 
如List<int>,实际FullName是System.Collections.Generic.List`1[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea78e]]
 
我期望的是:System.Collections.Generic.List<System.Int32>
 
所以写了个Type扩展类,处理FullName
 
 public static class TypeExt
    {
        public static string GetFullName(this Type type)
        {
            var str = string.Empty;
            if (type.IsGenericType)
            {
                //获取泛型定义
                //FullName:System.Collections.Generic.List`1
                str = type.GetGenericTypeDefinition().FullName;
                //获取所有泛型类型的数组
                var args = type.GetGenericArguments();
                //泛型类型的数组索引
                int argIndex = 0;
                while (true)
                {
                    var startIndex = str.IndexOf('`');
                    if (startIndex < 0) break;
                    //获取外部类的泛型数量
                    var argNum = System.Convert.ToInt32(str.Substring(startIndex + 1, 1));
                    string tmp = string.Empty;
                    tmp += "<";
                    for (int i = 0; i < argNum; i++, argIndex++)
                    {
                        if (i < argNum - 1)
                            tmp += $"{args[argIndex].GetFullName()},";
                        else
                            tmp += $"{args[argIndex].GetFullName()}";
                    }
                    tmp += ">";
                    str = str.Remove(startIndex, 2);
                    str = str.Insert(startIndex, tmp);
                }
            }
            else
            {
                str = type.FullName ?? string.Empty;
            }

            if (type.IsNested)
            {
                //替换嵌套类的+
                str = str.Replace('+', '.');
            }
            return str;
        }

    }

  

 
 
posted @ 2022-05-31 10:06  wanwanwhl  阅读(55)  评论(0编辑  收藏  举报