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

前端 未结 14 1652
抹茶落季
抹茶落季 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
    2021-01-30 07:20

    For C# 6.0 onwards, you can use Interpolated Strings to do this tricks.

    Example:

        Console.WriteLine("\n --- For REGULAR NOUNS --- \n");
        {
            int count1 = 1;
            Console.WriteLine($"I have {count1} apple{(count1 == 1 ? "" : "s")}.");
            int count2 = 5;
            Console.WriteLine($"I have {count2} apple{(count2 == 1 ? "" : "s")}.");
        }
    
        Console.WriteLine("\n --- For IRREGULAR NOUNS --- \n");
        {
            int count1 = 1;
            Console.WriteLine($"He has {count1} {(count1 == 1 ? "leaf" : "leaves")}.");
            int count2 = 5;
            Console.WriteLine($"He has {count2} {(count2 == 1 ? "leaf" : "leaves")}.");
        }
    

    Output:

     --- For REGULAR NOUNS --- 
    
    I have 1 apple.
    I have 5 apples.
    
     --- For IRREGULAR NOUNS --- 
    
    He has 1 leaf.
    He has 5 leaves.
    

    You can play around on my .NET Fiddle.
    For more details, go to Interpolated String documentation.

提交回复
热议问题