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

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

    I did a little bit of work with PluralizationService and came up with. I just made the PluralizationService static for performance and combined all.

    Reference System.Data.Entity.Design

      using System.Data.Entity.Design.PluralizationServices;
      using System.Reflection;
    
      public static class Strings
      {
        private static PluralizationService pluralizationService = PluralizationService.CreateService(System.Globalization.CultureInfo.CurrentUICulture);
        public static string Pluralize(this MemberInfo memberInfo)//types, propertyinfos, ect
        {
          return Pluralize(memberInfo.Name.StripEnd());
        }
    
        public static string Pluralize(this string name)
        {
          return pluralizationService.Pluralize(name); // remove EF type suffix, if any
        }
    
        public static string StripEnd(this string name)
        {
          return name.Split('_')[0];
        }
      }
    

提交回复
热议问题