c#采用toml做配置文件遇到的坑
這幾天在玩?zhèn)€程序,突然看到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類型的參數(shù)測試測試,魔咒來了。
Console.WriteLine("ServerAddress: " + toml.Get<TomlTable>("Client").Get<float>("floatXXX"));
讀取一切正常,
下一步呢?修改修改?于是看來看去有個Update函數(shù)
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也有這個莫名其妙的數(shù)字
百思不得其解,然后下載了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,這個。。。。
得出個結(jié)論,c#用toml文件讀取非整數(shù)字請用double,不要用float,decimal倒無所謂,反正編譯不過,切記不要用float。
特此記錄,避免打擊迷茫,也算一個玩程序中的不太有用知識點,算是記錄吧。
到此這篇關(guān)于c#采用toml做配置文件的坑過的文章就介紹到這了,更多相關(guān)c# toml配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#?基礎(chǔ)數(shù)據(jù)類型之字符串類型詳解
C#字符串作為引用類型卻常被當作值類型使用,探討其不可變性、字符串駐留及常用操作,本文給大家介紹C#?基礎(chǔ)數(shù)據(jù)類型之字符串類型,感興趣的朋友一起看看吧2026-05-05
C#實現(xiàn)高效讀取Word表格數(shù)據(jù)并導(dǎo)出為CSV/TXT
在.NET開發(fā)場景中,讀取 Word 文檔中的表格數(shù)據(jù)是辦公自動化、數(shù)據(jù)導(dǎo)入、報表生成等業(yè)務(wù)的高頻需求,本文將詳細介紹如何用 C# 結(jié)合 Free Spire.Doc for .NET 庫實現(xiàn) Word 表格讀取,有需要的小伙伴可以了解下2026-03-03
C#利用delegate實現(xiàn)Javascript的each方法
這篇文章主要為大家介紹了介紹了C#利用delegate實現(xiàn)Javascript的each方法,感興趣的朋友可以參考一下2016-01-01

