前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >dotnet 使用 TypeNameFormatter 库格式化输出反射泛型类型

dotnet 使用 TypeNameFormatter 库格式化输出反射泛型类型

作者头像
林德熙
发布2021-03-29 15:17:11
4610
发布2021-03-29 15:17:11
举报
文章被收录于专栏:林德熙的博客林德熙的博客

默认的反射输出带泛型的类型,都会使用反引号的字符串。使用 TypeNameFormatter 库可以输出贴近代码的输出

默认的类型的输出是和代码写的方法不相同,如获取 List<int> 类型的输出

代码语言:javascript
复制
Console.WriteLine(typeof(List<int>));
// 大概输出是 List`1[System.Int32]

而我期望输出的是 List<int> 的内容,使用 TypeNameFormatter 库的代码如下

代码语言:javascript
复制
    class Program
    {
        static void Main(string[] args)
        {
            var fType = typeof(List<F>);
            Console.WriteLine(fType.GetFormattedName());
            // 输出 List<F>
        }
    }

    class F
    {
        public string A { get; set; }
        public string B { get; set; }
        public string C { get; set; }
    }

使用 NuGet 搜 TypeNameFormatter 就可以找到这个库,需要加上命名空间

代码语言:javascript
复制
using TypeNameFormatter;

编辑 csproj 添加下面代码可以快速安装

代码语言:javascript
复制
  <ItemGroup>
    <PackageReference Include="TypeNameFormatter.Sources" Version="1.1.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

这是一个源代码包,按照之后,可以在 obj 文件夹找到代码。或者进入 GetFormattedName 方法定义,可以看到代码

这个库在 GitHub 开源,请看 https://github.com/stakx/TypeNameFormatter


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/dotnet-%E4%BD%BF%E7%94%A8-TypeNameFormatter-%E5%BA%93%E6%A0%BC%E5%BC%8F%E5%8C%96%E8%BE%93%E5%87%BA%E5%8F%8D%E5%B0%84%E6%B3%9B%E5%9E%8B%E7%B1%BB%E5%9E%8B.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档