• c#采用toml做配置文件的坑过


     

    这几天在玩个程序,突然看到c#采用图toml文件,好用,直观,确实也简单。

     

    不过。。。。。。

     

    github上示例写的

    TOML to TomlTable

    TOML input file:v

    EnableDebug = true
    
    [Server]
    Timeout = 1m
    
    [Client]
    ServerAddress = "http://127.0.0.1:8080"
    

    Code:

    var toml = Toml.ReadFile(filename);
    Console.WriteLine("EnableDebug: " + toml.Get<bool>("EnableDebug"));
    Console.WriteLine("Timeout: " + toml.Get("Server").Get("Timeout"));
    Console.WriteLine("ServerAddress: " + toml.Get("Client").Get<string>("ServerAddress"));
    

    Output:

    EnableDebug: True
    Timeout: 00:01:00
    ServerAddress: http://127.0.0.1:8080
    

    TomlTable is Nett's generic representation of a TomlDocument. It is a hash set based data structure where each key is represented as a string and each value as a TomlObject.

    Using the TomlTable representation has the benefit of having TOML metadata - e.g. the Comments - available in the data model.

     

    很好用,于是改了个float类型的参数测试测试,魔咒来了。

    Console.WriteLine("ServerAddress: " + toml.Get<TomlTable>("Client").Get<float>("floatXXX"));
    
    读取一切正常,
    下一步呢?修改修改?于是看来看去有个Update函数
    toml.Get<TomlTable>("Server").Update("
    floatXXX
    ",(double)fV);
    噩梦,于是1.1存进去变成了值 1.00999999046326,怎么测试都不对,这是什么鬼
    百度https://www.baidu.com/s?ie=UTF-8&tn=62095104_35_oem_dg&wd=1.00999999046326也有这个莫名其妙的数字
    
    百思不得其解,然后下载了https://github.com/paiden/Nett源码看看:
    

    // Values
    public static Result Update(this TomlTable table, string key, bool value)
    => Update(table, key, table.CreateAttached(value));

    public static Result Update(this TomlTable table, string key, string value)
    => Update(table, key, table.CreateAttached(value));

    public static Result Update(this TomlTable table, string key, long value)
    => Update(table, key, table.CreateAttached(value));

    public static Result Update(this TomlTable table, string key, double value)
    => Update(table, key, table.CreateAttached(value));

    public static Result Update(this TomlTable table, string key, DateTimeOffset value)
    => Update(table, key, table.CreateAttached(value));

    public static Result Update(this TomlTable table, string key, TimeSpan value)
    => Update(table, key, table.CreateAttached(value));

     

    琢磨出点门道来了,没有float类型啊,于是改为double,一切风平浪静,回归正常。

    OMG,这个。。。。

     

    得出个结论,c#用toml文件读取非整数字请用double,不要用float,decimal倒无所谓,反正编译不过,切记不要用float。

     

    特此记录,避免打击迷茫,也算一个玩程序中的不太有用知识点,算是记录吧。

    20240420

     

    
    
    


  • 相关阅读:
    Java中的数组
    # 数据结构
    python 上下文管理器
    2023年哪些渲染器更好用?3D新手适合的渲染器汇总
    java通过opencv解析二维码(微信开源解码工具)
    【数据挖掘竞赛】零基础入门数据挖掘-二手汽车价格预测
    如何判断一个对象是否为空
    2019java面试(六)
    Qt - 聊天室发送图片/文件
    3-4数据链路层-局域网
  • 原文地址:https://www.cnblogs.com/liqi/p/18148138