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

前端 未结 14 1627
抹茶落季
抹茶落季 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条回答
  •  迷失自我
    2021-01-30 07:18

    A bit late to the party, but I wrote a library called MessageFormat.NET that handles this.

    var str = @"You have {lives, plural, 
                         zero {no lives} 
                          one {one life} 
                        other {# lives}
                } left.";
    var result = MessageFormatter.Format(str, new {
        lives = 1337
    });
    

    The whitespace in the string surrounding the text is not required, but merely for readability.

    This is great when translating, as languages have different rules when it comes to pluralization.

提交回复
热议问题