我有一個程序,它保存它生成的雙精度文件並讀取下一次運行的文件。 問題是當它想要在不同的窗口中第一次讀取文件時,它不能管理不同窗口中的小數點符號,有些窗口使用象'。'這樣的符號。其中一些使用'/'作爲分隔符。 我該如何處理這個問題?不同的十進制符號C#
負載部分:
private void Load(string file)
{
if (File.Exists(file))
{
StreamReader reader = new StreamReader(file);
string line = reader.ReadLine();
//I think i should use IFormatProvider here.
m_GamesTrained = int.Parse(line);
//Some code here!but irrelevant to topic
reader.Close();
}
}
,並保存部分:
private void Save(string file)
{
StreamWriter writer = new StreamWriter(file, false);
m_LastGamesTrainedSave = m_GamesTrained;
writer.WriteLine(m_GamesTrained.ToString());
float[] contactWeights = m_ContactNetwork.GetWeights();
for (int i = 0; i < contactWeights.Length; i++)
{
//I think i should use IFormatProvider here too
writer.WriteLine(contactWeights[i].ToString());
}
writer.Close();
}
使用[ToString](https://msdn.microsoft.com/library/3ebe5aks.aspx)與固定的[IFormatProvider](https://msdn.microsoft.com/library/system.iformatprovider.aspx)像[CultureInfo.InvariantCulture](https://msdn.microsoft.com/library/system.globalization.cultureinfo.invariantculture.aspx)用於在系統之間寫入/讀取。 - 如果你沒有提供一個固定的IFormatProvider,它將使用CurrentUICulture,它可能在不同的系統上有所不同,並且會導致''''和'.'(不會看到'/'作爲小數分隔符)。 – Corak
Btw。對困惑感到抱歉。在標題中有'decimal',文本中有'double',代碼中有'float'(爲什麼'float'?)。所有這些值類型都實現了[IFormattable](https://msdn.microsoft.com/library/system.iformattable.aspx),因此您可以爲它們提供一個固定的IFormatProvider。 - 讀完之後,您可以將同一個IFormatProvider添加到[Parse](https://msdn.microsoft.com/library/bh4863by.aspx)方法中。 – Corak
在Windows 8.1中,您可以看到'/'作爲分隔符。我如何在我的代碼中使用'IformatProvider'? –