简体   繁体   English

将对象转换为具有指定区域性的字符串

[英]Converting an object to string with a specified culture

有没有更好的方法将 Object 类型的变量转换为具有指定文化的字符串(这与 Thread 的默认文化不同),而不是使用诸如 1) 尝试将对象强制转换为所有类型的丑陋方法支持ToString(CultureInfo)重载或 2) 临时设置线程的默认文化?

You only have to cast it to the IConvertible interface:您只需将其转换为IConvertible接口:

object o = ...;
string s = ((IConvertible)o).ToString(cultureInfo);

I think the best way is to use Convert.ToString(obj, cultureInfo).我认为最好的方法是使用 Convert.ToString(obj,cultureInfo)。 It makes all the casting under the hood.它使引擎盖下的所有铸件成为可能。

public static string ToString(Object value, IFormatProvider provider) {
    IConvertible ic = value as IConvertible;
    if (ic != null) 
        return ic.ToString(provider);
    IFormattable formattable = value as IFormattable;
    if (formattable != null) 
        return formattable.ToString(null, provider);
    return value == null? String.Empty: value.ToString();
}

Source: https://referencesource.microsoft.com/#mscorlib/system/convert.cs,6a1a2c3ac58e60dd来源: https : //referencesource.microsoft.com/#mscorlib/system/convert.cs,6a1a2c3ac58e60dd

string.Format(culture, "{0}", obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM