Parse Boolean C# Culture verdadero

2019-07-07 02:21发布

问题:

I am trying to run this exact line, and it isn't working. Anyone know the reason why?

Convert.ToBoolean("verdadero", new System.Globalization.CultureInfo("ES-MX"));

I am parsing this from an xml file generated by a program that has many languages installed, and so it will use "true" in "EN-US" culture or "verdadero" in "ES-MX".

回答1:

Interesting. Running Convert.ToBoolean through a decompiler emits this:

/// <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);
}

This makes it look like the IFormatProvider is completely disregarded.

I'm tempted to say it's a bug in the framework, but experience has taught me that I'm usually missing something when I come to that conclusion...