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

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

    With the newfangled interpolated strings, I just use something like this:

    // n is the number of connection attempts
    Console.WriteLine($"Needed {n} attempt{(n!=1 ? "s" : "")} to connect...");
    

    EDIT: just ran across this answer again--since I originally posted this, I've been using an extension method that makes it even easier. This example is ordered by peculiarity:

    static class Extensions {
        /// 
        /// Pluralize: takes a word, inserts a number in front, and makes the word plural if the number is not exactly 1.
        /// 
        /// "{n.Pluralize("maid")} a-milking
        /// The word to make plural
        /// The number of objects
        /// An optional suffix; "s" is the default.
        /// An optional suffix if the count is 1; "" is the default.
        /// Formatted string: "number word[suffix]", pluralSuffix (default "s") only added if the number is not 1, otherwise singularSuffix (default "") added
        internal static string Pluralize(this int number, string word, string pluralSuffix = "s", string singularSuffix = "")
        {
            return $@"{number} {word}{(number != 1 ? pluralSuffix : singularSuffix)}";
        }
    }
    
    void Main()
    {
        int lords = 0;
        int partridges = 1;
        int geese = 1;
        int ladies = 8;
        Console.WriteLine($@"Have {lords.Pluralize("lord")}, {partridges.Pluralize("partridge")}, {ladies.Pluralize("lad", "ies", "y")}, and {geese.Pluralize("", "geese", "goose")}");
        lords = 1;
        partridges = 2;
        geese = 6;
        ladies = 1;
        Console.WriteLine($@"Have {lords.Pluralize("lord")}, {partridges.Pluralize("partridge")}, {ladies.Pluralize("lad", "ies", "y")}, and {geese.Pluralize("", "geese", "goose")}");
    }
    

    (formats are the same). The output is:

    Have 0 lords, 1 partridge, 8 ladies, and 1 goose
    Have 1 lord, 2 partridges, 1 lady, and 6 geese
    

提交回复
热议问题