简体   繁体   中英

.ToString() and .ToString(CultureInfo.CurrentCulture)

I must use .ToString(CultureInfo.CurrentCulture) in every number to string conversion for example. Can I somehow override .ToString() so that I will get no more messages like culture in string conversion explicitly?

For example, now I have to change every

myNumValue.Count.ToString();

to

myNumValue.Count.ToString(CultureInfo.CurrentCulture);

It doesn't make any sense to replace ToString() with ToString(CultureInfo.CurrentCulture) cause this is exactly what ToString() already does.

If you don't put a defined culture (maybe through a user selection) into your code simply stick to the first method.

The point of this rule is to make an explicit choice of culture for every formatting and parsing operation. If you try to systematically swap implementations to "trick" the rule, you'll simply end up sweeping potential problems under the rug. As suggested by Lonli-Lokli, you may want to consider using extension methods if you don't like reading ToString calls with a culture arguments, but you should have a distinct extension method for each culture you support. eg: ToUIString() -> ToString(CultureInfo.CurrentCulture) and ToInvariantString() -> ToString(CultureInfo.InvariantCulture)

如果您指的是来自代码分析的消息,那么您可以禁用特定规则。

您可以创建扩展方法 ToStringEx 并调用具有指定区域性的常用方法。

You could write a ToStringInvariant and a ToStringCurrent extension methods with one override for each type to convert: int, double, decimal, etc. It is a matter of minutes with copy and paste. DateTime can eventually be handled the same way.

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