C#读取toml文件

Toml 格式太适合作为config文件了, nuget 上排名前两个类库是 Tomlyn 和 Nett.

Tomlyn 使用

试了一下 Tomly, 它在做文件和Model映射时, 会强制toml文件必须按照snake风格写, C# Model类必须要按照Pascal风格写, 不然在读取时直接抛出异常.

Toml 文件 C# model
[some_table] SomeTable

看了官方文档后, 决定放弃. 官方文档: https://github.com/xoofx/Tomlyn/blob/main/doc/readme.md

Nett 总体感受

Nett 项目使用体验简直太好了, 默认情况下, key和属性的映射将按照名字大小写完全匹配方式完成, 不会像 Tomlyn 库强制. 当然
Nett 支持 table array, API 设计非常简洁. 唯一的问题是: 作者已经放弃了后续的开发, 好在基本功能都有了.
github 项目 https://github.com/paiden/Nett
文档主页 https://paiden.github.io/Nett/howto/read.html

Nett 快速上手

  1. 安装 Install-Package Nett
  2. 定义一个 toml 文件
    包含了缺省table 和一个命名 table 和一个 table array.
EnableDebug = true

[Server]
Timeout = 1m

[[people]]
name = "Alice"
age = 25

[[people]]
name = "Bob"
age = 42
  1. C# 读取 toml

定义 Model 类

public class Person
{
    public string name { get; set; } 
    public int age { get; set; }
}

将 table array 映射到model list中

TomlTableArray peopleTable = Toml.ReadFile("people.toml").Get<TomlTableArray>("people");

List<Person> people = peopleTable.Items
                                .Select(item => item.Get<Person>())
                                .ToList();

猜你喜欢

转载自blog.csdn.net/csdnharrychinese/article/details/129906305