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

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

    See the Inflector class that is part of Castle ActiveRecord. It is licensed under the Apache license.

    It has a set of regular expression rules that define how words are pluralized. The version I have used has some errors in these rules though, e.g. it has a 'virus' → 'virii' rule.

    I have three extension methods which wrap Inflector, the first of which may be right up your street:

        /// 
        /// Pluralises the singular form word specified.
        /// 
        /// The singular form.
        /// The count.
        /// The word, pluralised if necessary.
        public static string Pluralise(this string @this, long count)
        {
            return (count == 1) ? @this :
                                  Pluralise(@this);
        }
    
        /// 
        /// Pluralises the singular form word specified.
        /// 
        /// The singular form word.
        /// The plural form.
        public static string Pluralise(this string @this)
        {
            return Inflector.Pluralize(@this);
        }
    
        /// 
        /// Singularises the plural form word.
        /// 
        /// The plural form word.
        /// Th singular form.
        public static string Singularise(this string @this)
        {
            return Inflector.Singularize(@this);
        }
    

提交回复
热议问题