资源文件的String.Format和占位符在.NET文件、资源、String、Format

2023-09-05 01:03:00 作者:人美B遭罪〃

据我所知,使用资源文件来处理动态数据的本地化字符串在.NET的最好办法是让在resources.resx文件本地化的字符串中有一个占位符的 LOREM {0 }存有的并在code,要这样处理:的String.Format(Resources.My_Localized_Key,myvalue的);

As far as I know, the best way to handle dynamic data in a localized string using resource files in .NET is to have your localized string in the resources.resx file with a placeholder in it: Lorem {0} ipsum. and in your code, to handle it this way: string.Format(Resources.My_Localized_Key, myValue);.

我的关注点如下:

1 /如何确保占位符将被实际值替换?例如,在你的团队一个新的开发人员可能需要使用这个本地化的字符串中的一些新资料片code,他的写作,但没有意识到,他必须用一些数据给它。也没有什么样的数据。

1/ How to be sure that the placeholder will be replaced by an actual value? For example, a new developer in your team may need to use this localized string in some new piece of code he's writing but not being aware he has to feed it with some data. Nor what kind of data.

2 /运行后,如果由于某种原因,本地化的字符串修改的 LOREM {0}存有{1} 的,我们如何才能保证整个应用该字符串的所有用途将被更新?

2/ If later, for some reasons, the localized string changes to Lorem {0} ipsum {1}., how can we ensure that all uses of this string across the application will be updated?

有没有更好的方式来处理呢?例如一种方法来处理这​​些占位符在强类型的方式,而无需使用反射或不必解析本地化字符串的内容...?或者是它只是做到这一点?

Is there any better way to handle this? For example a way to handle these placeholders in a strongly-typed manner without having to use reflection or having to parse the content of the localized string...? Or is it just the way to do it?

推荐答案

在实践中,对于第1期开发商并不可能会重用一个字符串,而不检查其内容,并且如果他们这么做,他们可能会发现它们运行时,占位符他们的code(或QA会)。所以这是不可能的,也不会是世界末日。

In practice, for issue 1 developers would not be likely to reuse a string without checking its content, and if they did they would probably notice the placeholder when they run their code (or QA would). So it's unlikely and wouldn't be the end of the world.

有关问题2,你可以在Visual Studio中使用查找用法,对于它创建的资源找到它使用的每一个地方,确保正确的数量(并序)的参数自动生成的属性是有无处不在它的使用。但总体上看资源字符串没有得到重用那么多呢(它实际上是不建议重复使用在不同的上下文本地化的文本,因为翻译可能需要在不同情况下进行更改,由于语言的规则或例如空间限制)。

For issue 2 you could use "Find Usages" in Visual Studio for the auto-generated property that it creates for the resource to find every single place it's used and make sure the right number (and order) of parameters is there everywhere it's used. But generally speaking resource strings don't get reused that much anyway (it's actually not recommended to reuse localizable text in different contexts, as the translations may need to be changed in different contexts, due to linguistic rules or space restrictions for example).

另一个风险我想看到的是,翻译可以省略或陷入困境的占位符,这将是难以检测。但是,这将是一个本地化的错误的一个例子。还有很多其他的东西本地化程序的时候,可以去错了,往往没有肯定的方式来加以防范。

Another risk I would see is that a translator may omit or mess up the placeholders, which would be harder to detect. But this would be just one example of a localization bug... There are plenty of other things that can go wrong when localizing an app and there is often no sure way to guard against them.