首页 > Windows开发 > 详细

C#自定义格式提供器

时间:2020-04-11 17:29:34      阅读:51      评论:0      收藏:0      [点我收藏+]

将数字转化为单词

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));

结果

技术分享图片

 

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

 

C#自定义格式提供器

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!