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

走远了吗. 提交于 2019-11-28 22:42:50

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

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

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!