簡體   English   中英

將對象轉換為具有指定區域性的字符串

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

有沒有更好的方法將 Object 類型的變量轉換為具有指定文化的字符串(這與 Thread 的默認文化不同),而不是使用諸如 1) 嘗試將對象強制轉換為所有類型的丑陋方法支持ToString(CultureInfo)重載或 2) 臨時設置線程的默認文化?

您只需將其轉換為IConvertible接口:

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

我認為最好的方法是使用 Convert.ToString(obj,cultureInfo)。 它使引擎蓋下的所有鑄件成為可能。

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

來源: 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