5

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

 3 years ago
source link: https://lindexi.gitee.io/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
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
dotnet 使用 TypeNameFormatter 库格式化输出反射泛型类型

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

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

Console.WriteLine(typeof(List<int>));
// 大概输出是 List`1[System.Int32]

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

    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 就可以找到这个库,需要加上命名空间

using TypeNameFormatter;

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

  <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 ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号
lindexi%2F201985113622445

欢迎进入 Eleven 老师组建的 .NET 社区
lindexi%2F20209121930471745.jpg

以上广告全是友情推广,无盈利


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK