C# .ToString() 和 .ToString(CultureInfo.CurrentCulture)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9294290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:45:51  来源:igfitidea点击:

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

c#.netcode-analysistostring

提问by senzacionale

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?

例如,我必须.ToString(CultureInfo.CurrentCulture)在每个数字中使用字符串转换。我可以以某种方式覆盖,.ToString()以便我不会在字符串转换中显式地获得更多像文化这样的消息吗?

For example, now I have to change every

例如,现在我必须改变每一个

myNumValue.Count.ToString();

to

myNumValue.Count.ToString(CultureInfo.CurrentCulture);

采纳答案by Nicole Calinoiu

The point of this rule is to make an explicitchoice 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 ToStringcalls with a culture arguments, but you should have a distinct extension method for each culture you support. e.g.: ToUIString()-> ToString(CultureInfo.CurrentCulture)and ToInvariantString()-> ToString(CultureInfo.InvariantCulture)

这条规则的重点是为每个格式化和解析操作做出明确的文化选择。如果您尝试系统地交换实现以“欺骗”规则,您最终只会将潜在问题扫地出门。正如 Lonli-Lokli 所建议的,如果您不喜欢阅读ToString带有文化参数的调用,您可能需要考虑使用扩展方法,但您应该为支持的每种文化使用不同的扩展方法。例如:ToUIString()->ToString(CultureInfo.CurrentCulture)ToInvariantString()->ToString(CultureInfo.InvariantCulture)

回答by abatishchev

If you mean a message from Code Analysis, then you can disable a particular rule.

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

回答by Lonli-Lokli

You can create extension method, ToStringEx and call usual method with specified culture.

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

回答by Oliver

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

替换ToString()为没有任何意义,ToString(CultureInfo.CurrentCulture)因为这正是ToString()已经发生的事情。

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

如果您没有将定义的文化(可能通过用户选择)放入您的代码中,只需坚持使用第一种方法。

回答by pasx

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.

您可以编写一个 ToStringInvariant 和一个 ToStringCurrent 扩展方法,为每种类型转换一个覆盖:int、double、decimal 等。复制和粘贴只需几分钟。DateTime 最终可以以相同的方式处理。