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

前端 未结 14 1649
抹茶落季
抹茶落季 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:17

    I wrote an open-source library called SmartFormat that does exactly that! It's written in C# and is on GitHub: http://github.com/scottrippey/SmartFormat

    Although it supports several languages, English "plural rules" are the default. Here's the syntax:

    var output = Smart.Format("You have {0} {0:life:lives} left.", player.Lives);
    

    It also supports "zero" quantity, and nested placeholders, so you could do:

    var output = Smart.Format("You have {0:no lives:1 life:{0} lives} left.", player.Lives);
    

提交回复
热议问题