0

我试图让我的程序更兼容,因为我最终改变了很多小东西,例如,

使用textBox.Text = Convert.ToString(value)代替= "value"

获取当前用户小数点分隔符并将其replace用于tryparse

char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

float.TryParse(str.Replace(",", sepdec.ToString()).Replace(".", sepdec.ToString()), out testvariable;

但是,当您已经编写了大部分程序而不用担心它时,这些解决方案很难实现。

所以我试图找到使整个代码兼容的方法,而不必编辑每tryparse一个textbox

我尝试执行以下操作:

//Get the current user decimal separator before the program initializes
char sepdec = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

//Create a current culture clone and change the separator to whatever the user has in his regional options, before the initializing the component

  public Form1()
  {
  System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
  customCulture.NumberFormat.NumberDecimalSeparator = sepdec.ToString();

  System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

  InitializeComponent();
  }

但我已经对此进行了测试,它并没有真正做任何事情。它不应该让程序理解类似的东西ok, now you use dot as your decimal separator altough you have values in textBox as "2,5" 吗?

4

1 回答 1

1

好的,现在您使用点作为小数分隔符,尽管您在 textBox 中的值为“2,5”

确切地。

float.TryParseCurrentCulture如果您不使用任何设置,方法将使用您的设置IFormatProvider

如果您尝试解析为"2,5"浮动而没有任何.IFormatProviderCurrentCulture,NumberDecimalSeparator

如果您尝试解析"2.5"为浮动,您可以使用文化作为另一个已经具有 . 作为NumberDecimalSeparator(like InvariantCulture),或者您可以.Clone()(CurrentCulture像您所做的那样) 并将其NumberDecimalSeparator属性设置为.并将此克隆的区域性用作float.TryParse重载中的另一个参数。

于 2015-04-05T19:12:11.373 回答