简体   繁体   中英

Is CultureInfo.CurrentCulture really necessary in String.Format()?

How do you think is really necessary to provide IFormatProvider in method String.Format(string, object) ?

Is it better to write full variant

String.Format(CultureInfo.CurrentCulture, "String is {0}", str);

or just

String.Format("String is {0}", str);

?

In general, you will want to use InvariantCulture if the string you are generating is to be persisted in a way that is independent of the current user's culture (eg in the registry, or in a file).

You will want to use CurrentCulture for strings that are to be presented in the UI to the current user (forms, reports).

Subtle bugs can arise if you use CurrentCulture where you should be using InvariantCulture: bugs that only come to light when you have multiple users with different cultures accessing the same registry entry or file, or if a user changes his default culture.

Explicitly specifying CurrentCulture (the default if the IFormatProvider argument is omitted), is essentially documentation that demonstrates that you have considered the above and that the string being generated should use the current user's culture. That's why FxCop recommends that you should specify the IFormatProvider argument.

If you do not specify the IFormatProvider (or equivalently pass null ) most argument types will eventually fall through to being formatted according to CultureInfo.CurrentCulture . Where it gets interesting is that you can specify a custom IFormatProvider that can get first crack at formatting the arguments, or override the formatting culture depending on other context.

Note that CultureInfo.CurrentCulture affects argument formatting, not resource selection; resource selection is controlled by CultureInfo.CurrentUICulture .

不,您不需要指定文化,除非您的字符串包含文化特定元素,如小数分隔符,货币等,必须根据文化呈现。

It is especially useful if you care about localization (Globalization) in your application. That is, if you want your app to support multiple languages and culture specific formats, then you should use that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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