FxCop CA1305:CurrentCulture 与 CurrentUICulture
所以,我有一些用于本地化的资源文件。它们是可以格式化的字符串。
例如:
MyResource.resx
Title: "MyApp - Ver: {0}"
然后我通过这样做返回它:
public String Title
{
get { return String.Format(CultureInfo.CurrentUICulture, MyResources.Title, 1); }
}
我理解 CurrentUICulture 和 CurrentCulture 之间的区别,但 FxCop 告诉我使用 CurrentCulture 代替?
So, I have a few resource files for localization. They're strings that can be formatted.
For example:
MyResource.resx
Title: "MyApp - Ver: {0}"
I then return it by doing like so:
public String Title
{
get { return String.Format(CultureInfo.CurrentUICulture, MyResources.Title, 1); }
}
I understand the difference between CurrentUICulture and CurrentCulture, but FxCop is telling me to use CurrentCulture instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在某种程度上,FxCop 是正确的:在这种情况下,您不应该使用
CurrentUICulture
。正如其他人已经说过的,CurrentCulture
用于区域设置感知格式,而CurrentUICulture
用于从资源中读取可翻译字符串。您在这里所做的是格式化数字,因此 FxCop 抱怨您使用了不正确的
CultureInfo
。不幸的是,FxCop 没有告诉您的是,您实际上应该使用CultureInfo.InvariantCulture
。为什么?因为版本号是不依赖于Locale的东西。您总是会看到像 1.9 这样的东西,而不是像 1,9 这样的东西。因此,InvariantCulture
是正确的选择。微软甚至提供了特定的类来存储版本信息 - 奇怪的是,它的名称是
Version
(AFAIR 它位于System
命名空间中)。当您执行ToString()
时,这将始终向您显示版本号,就像我之前提到的那样。当您实例化它时,它的构造函数还需要区域设置不变的版本字符串。To some extent FxCop is right: you should not use
CurrentUICulture
in this case. As others already said,CurrentCulture
is meant for Locale-aware formatting, whereasCurrentUICulture
is meant for reading translatable strings from resources.What you did here, was formatting number, therefore FxCop complains that you used incorrect
CultureInfo
. Unfortunately, what FxCop did not tell you is, you should in fact useCultureInfo.InvariantCulture
. Why? Because version number is something that does not depend on Locale. You will always see something like 1.9 and not something like 1,9. ThusInvariantCulture
is the way to go.Microsoft even provided specific class to store version information - oddly enough its name is
Version
(AFAIR it is inSystem
namespace). This will always present you version numbers like I mentioned before, when you doToString()
. Its constructor also expects Locale-invariant version string when you instantiate it.String.Format
通常用于数字或日期格式化,它基于CurrentCulture
而不是CurrentUICulture
。String.Format
is often going to be used for numeric or date formatting, which is based onCurrentCulture
rather thanCurrentUICulture
.另一件事是,
CurrentUICulture
可以是中立文化,而CurrentCulture
始终是特定文化。XXXFormatInfo
类型不适用于中性区域性,并且会引发NotSupportedException
异常。Another thing is that
CurrentUICulture
can be a neutral culture whileCurrentCulture
is always a specific culture.The
XXXFormatInfo
types do not work with neutral cultures and will raise aNotSupportedException
exception.