C#自定义格式提供器

将数字转化为单词

public class WordFormatProvider : IFormatProvider, ICustomFormatter
    {
        static readonly string[] _numberWords= new string[] { "zero","one","two","three","four","five","six","seven", "eight", "nine","ten","minus","point"};
        IFormatProvider _parent;
        public WordFormatProvider() :this(CultureInfo.CurrentCulture) { }

        public WordFormatProvider(IFormatProvider parent)
        {
            _parent = parent;
        }
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            if (arg == null || format != "W") return string.Format(_parent, "{0:" + format + "}", arg);
            StringBuilder builder = new StringBuilder();
            string digitList = string.Format(CultureInfo.InvariantCulture, "{0}", arg);
            foreach (char digit in digitList)
            {
                int i = "0123456789-.".IndexOf(digit);
                if (i == -1) continue;
                if (builder.Length > 0) builder.Append(' ');
                builder.Append(_numberWords[i]);
            }
            return builder.ToString();
        }

        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter)) return this;
            return null;
        }
    }

测试

 IFormatProvider fp = new WordFormatProvider();
  Console.WriteLine(string.Format(fp, "{0:C} in words is{0:W}", -123.45));

结果

 注意自定义格式提供器只能在组合格式字符串中使用。

原文地址:https://www.cnblogs.com/aqgy12138/p/12679948.html