Clever way to append 's' for plural form in .Net (syntactic sugar)

前端 未结 14 1628
抹茶落季
抹茶落季 2021-01-30 06:53

I want to be able to type something like:

Console.WriteLine(\"You have {0:life/lives} left.\", player.Lives);

instead of

Consol         


        
14条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 07:15

    If your application is English on you can use all the solutions shown here. However if you plan to localize the application the plural enabled message must be done in a proper way. This means that you may need multiple patterns (from 1 to 6) depending on the language and the rule to choose what the pattern is used depends on the language.

    For example in English you would have two patterns

    "You have {0} live left" "You have {0} lives left"

    Then you would have a Format function where you pass these two patterns with the liveAmount variable.

    Format("You have {0} live left", "You have {0} lives left", liveAmount);
    

    In a real application you would not hard code the string but would use resource strings.

    Format would know what the active language is and if English it would use

    if (count == 1)
      useSingularPattern
    else
      usePluralPattern
    

    To implement this yourself is a bit complex bu you don't have to. You can you an open source project I have made

    https://github.com/jaska45/I18N

    By using it you can easily get the string

    var str = MultiPattern.Format("one;You have {0} live left;other;You have {0} lives left", liveAmount);
    

    That's it. The library knows what pattern to use depending on the passed liveAmount paramter. The rules have been extracted from CLDR into library .cs file.

    If you want to localize the application you just put the multi pattern string into .resx and let the translator to translate it. Depending on the target language the multi pattern string might contains 1, 2, 3, 4, 5 or 6 patterns.

提交回复
热议问题