我的代码库中有一些代码用于评估使用Datatable method传递给它的表达式,因为[在此插入历史原因]。该方法的简短版本如下。
当我的应用程序在非美国/澳大利亚/英国的区域设置(如西班牙)中运行时,其中句点以浮点数替换逗号,则代码不起作用。
有没有办法让Datatable方法更具文化意识?或者在事情发展到目前为止,我是否仍然坚持将数据解析为不变文化?
void Main()
{
// This works
CompareInACulture("en-US"); // US English
// This doesn't
CompareInACulture("es-ES"); // Spanish
}
// This is testing code for the purposes of exploring the issue
// With this code I am comparing the value 1.1 with 1 and seeing if the first value is larger
// than the second. The code fails when in Spanish locale.
public void CompareInACulture(string cultureCode)
{
var value1 = 1.1;
var value2 = 1;
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureCode);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCode);
var compareString = value1.ToString() + ">" + value2.ToString();
// My current approach is to use an invariantCulture here, but I'm not satisfied it is the best approach
// var compareString = value1.ToString(CultureInfo.InvariantCulture) + ">" + value2.ToString(CultureInfo.InvariantCulture);
// I'd rather do something with the ExpressionEval class to let it know that the string it is workign with is from another culture.
Console.WriteLine($"Now comparing {compareString}");
var evaluator = new ExpressionEval();
var result1 = evaluator.Evaluate(compareString, out var passOrFail);
Console.WriteLine($"Evaluate returned {result1} and passOrFail is {passOrFail}.");
}
// This is a simplified version of the class that's doing the actual job. I can tweak this, but not radically change it.
public class ExpressionEval
{
string _lastErrorText = "";
public string LastErrorText => _lastErrorText;
public bool Evaluate(string psExpression, out bool pbResult)
{
pbResult = false;
try
{
var loDataTable = new DataTable();
var loDataColumn = new DataColumn("Eval", typeof(bool), psExpression);
loDataTable.Columns.Add(loDataColumn);
loDataTable.Rows.Add(0);
pbResult = (bool)(loDataTable.Rows[0]["Eval"]);
return true;
}
catch (Exception ex)
{
// do stuff
Console.WriteLine(ex.Message);
return false;
}
}
}
我希望DataTable.locale可以提供帮助,但设置它似乎无法实现任何目标。 this Microsoft site的评论部分地说“在包含表达式的列中,使用了InvariantCulture。忽略了CurrentCulture。”