随笔 - 1  文章 - 0 评论 - 1 阅读 - 418
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

 

这几天在玩个程序,突然看到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<TomlTable>("Server").Get<TimeSpan>("Timeout"));
Console.WriteLine("ServerAddress: " + toml.Get<TomlTable>("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<TomlBool> Update(this TomlTable table, string key, bool value)
=> Update(table, key, table.CreateAttached(value));

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

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

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

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

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

 

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

OMG,这个。。。。

 

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

 

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

20240420

 





posted on   glacierstream  阅读(418)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
点击右上角即可分享
微信分享提示