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

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

    You may checkout the PluralizationService class which is part of the .NET 4.0 framework:

    string lives = "life";
    if (player.Lives != 1)
    {
        lives = PluralizationService
            .CreateService(new CultureInfo("en-US"))
            .Pluralize(lives);
    }
    Console.WriteLine("You have {0} {1} left", player.Lives, lives);
    

    It is worth noting that only English is supported for the moment. Warning, this don't work on the Net Framework 4.0 Client Profile!

    You could also write an extension method:

    public static string Pluralize(this string value, int count)
    {
        if (count == 1)
        {
            return value;
        }
        return PluralizationService
            .CreateService(new CultureInfo("en-US"))
            .Pluralize(value);
    }
    

    And then:

    Console.WriteLine(
        "You have {0} {1} left", player.Lives, "life".Pluralize(player.Lives)
    );
    

提交回复
热议问题