c#採用toml做配置檔案的坑過

glacierstream發表於2024-04-20

這幾天在玩個程式,突然看到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





相關文章