解析 C# 中的布尔值,区域设置为真。

4
我试图运行这一行代码,但是它没有起作用。有人知道原因吗?
Convert.ToBoolean("verdadero", new System.Globalization.CultureInfo("ES-MX"));

我正在解析来自一个安装了多种语言的程序生成的xml文件,因此它将在"EN-US"文化中使用"true"或在"ES-MX"中使用"verdadero"。


1
与论坛网站不同的是,我们在 [so] 上不使用“感谢”、“感激任何帮助”或签名。参见“应该从帖子中删除“Hi”,“thanks”,标语和称谓吗? - John Saunders
XML文档是否有XML模式(例如XSD文件)或其他规范?如果有,它应该列举出所有可能的值。 - Tom Blodget
1个回答

3
有趣。将 Convert.ToBoolean 运行通过反编译器产生以下结果:
/// <summary>
/// Converts the specified string representation of a logical value to its Boolean equivalent, using the specified culture-specific formatting information.
/// </summary>
/// 
/// <returns>
/// true if <paramref name="value"/> equals <see cref="F:System.Boolean.TrueString"/>, or false if <paramref name="value"/> equals <see cref="F:System.Boolean.FalseString"/> or null.
/// </returns>
/// <param name="value">A string that contains the value of either <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>. </param><param name="provider">An object that supplies culture-specific formatting information. This parameter is ignored.</param><exception cref="T:System.FormatException"><paramref name="value"/> is not equal to <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>. </exception><filterpriority>1</filterpriority>
[__DynamicallyInvokable]
public static bool ToBoolean(string value, IFormatProvider provider)
{
  if (value == null)
    return false;
  else
    return bool.Parse(value);
}

这使得似乎完全忽略了IFormatProvider。
我倾向于认为这是框架中的 bug,但经验告诉我,在做出这个结论时我通常会遗漏一些东西...

很遗憾,我没有看到任何好的选择。https://dev59.com/I3RB5IYBdhLWcg3w26x3 - Rob H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接