这几天在玩个程序,突然看到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