.NET equivalent of choices in Java resource bundles?

心不动则不痛 提交于 2019-12-22 10:14:03

问题


In Java resource bundles I may have the following Resource Bundle definitions:

en_GB - British English

jobs.search.resultstr = There {1,choice,0#are no jobs|1#is one job|1<are {1,number,integer} jobs} for your search

ceb_PH - Cebuano

jobs.search.resultstr = Adunay {1,choice,0#mga walay mga|1#mao ang 1 nga|1<{1,number,integer}} trabaho alang sa {1,choice,0#inyong mga|1#imong|1<inyong mga} search

The code I would use to extract the resource would make choices based on the input data and format the string correctly resulting in one of three different outputs.

pseudo code:

myResultStr = resourceBundle.getResource("jobs.search.resultStr", jobs.recordCount)

This would result in one of the following strings being output dependent on chosen locale and number of results returned.

en_GB

  1. There are no jobs for your search
  2. There is one job for your search
  3. There are 2 jobs for your search

or

ceb_PH

  1. Adunay mga walay mga trabaho alang sa inyong mga search
  2. Adunay mao ang 1 nga trabaho alang sa imong search
  3. Adunay 2 trabaho alang sa inyong mga search

I'm relatively new to .NET development and I've been looking at the .NET .resource and .resx approaches to localisation and I don't seem to be able to find any hint as to how I can achieve the same level of localisation flexibility as I've illustrated above within the .NET framework.

Any guidance and pointers as to how I could achieve this in .NET would be most welcome.

Thanks


回答1:


The way I solved this was indeed to use the CustomFormatter to implement an equivalent of ChoiceFormat which is used by a custom ResourceBundle object to proxy access to the .NET resx files. By implementing a Pluraliser object hierarchy covering all the languages I need (and more in the future) along with ChoiceFormat, I can localise strings accurately.

The code looks a bit like this...

String.Format(new ChoiceFormatProvider(Session["CultureInfo"]), rb.GetString("resxkey", Session["CultureInfo"]), new object[] { 5 });

The strings returned by GetString are localised by the resx file but are then processed by the custom formatter and they look like this....

{0:choice,0#zero str|1#one str|1<more than one}

Taking this further, I can process strings formatted like so...

{0:plural,zero#zero str|one#singular str|two#dual str|few#few str|many#many str|other#other plural str}

These two features coupled with a set of custom pluraliser objects allow for very complex localisation features to be implemented.



来源:https://stackoverflow.com/questions/18231828/net-equivalent-of-choices-in-java-resource-bundles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!