Why doesn't object have an overload that accepts IFormatProvider?

前端 未结 3 1197
情话喂你
情话喂你 2020-12-15 03:53

When converting for instance a decimal to a string, you use the CultureInfo.InvariantCulture and pass it as an IFormatProvider

相关标签:
3条回答
  • 2020-12-15 04:32

    Try to cast your value to IFormattable:

    foreach (var property in typeof(Order).GetProperties(BindingFlags.Public | BindingFlags.Instance).
           Where(c => ValidTypes.Contains(c.PropertyType)))
    {
        var value = property.GetValue(order, null);
        if (value != null)
        {
            var formattable = value as IFormattable;
            writer.WriteElementString(property.Name, 
            formattable == null ? value.ToString() : formattable.ToString(null, CultureInfo.InvariantCulture));
        }
    }
    
    0 讨论(0)
  • 2020-12-15 04:36

    Handy extension method of Peter's solution (modified to test also for IConvertible).

    public static string ToInvariantString(this object obj)
    {
        return obj is IConvertible ? ((IConvertible)obj).ToString(CultureInfo.InvariantCulture)
            : obj is IFormattable ? ((IFormattable)obj).ToString(null, CultureInfo.InvariantCulture)
            : obj.ToString();
    }
    
    0 讨论(0)
  • 2020-12-15 04:39

    Try one of these:

    string valueString = XmlConvert.ToString(value);
    string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
    

    XmlConvert.ToString() is made for XML, so it will keep things closer to the XML spec, such as using "true" instead of "True". However, it is also more brittle than Convert.ToString(). For example, this will throw an exception because of the UTC time:

    XmlConvert.ToString(DateTime.UtcNow)
    

    but this works:

    XmlConvert.ToString(DateTime.UtcNow, "o")
    
    0 讨论(0)
提交回复
热议问题