.Net关于几种格式化字符串

在.Net中将一个对象格式化为字符串有以下方式:
1,String.Format(string format, params object[] args)以及几种变形
     这种格式化要求args能实现了IFormattable接口
2,string Format(IFormatProvider provider, string format, params object[] args)
     这种格式化要求提供一个自定义的格式化功能
3,Object.ToString()
     众所周知的,调用了虚方法


下面例子可以显示这几种格式化功能的具体使用时机与实现方法
加入我们要格式化手机号码,众所周知,手机号码是11位的连续整数,但是有时候需要用139-2212-0987的格式进行显示,下面具体的代码:
首先是3个类,公共完成格式化功能:


 

        class ModilePhone:IFormattable
        {
            public string phone = "15115226678";
            string IFormattable.ToString(string format, IFormatProvider formatProvider)
            {
                if (formatProvider == null)
                    formatProvider = System.Globalization.CultureInfo.CurrentCulture;
                if (format == "G")
                    return string.Format("From IFormattable[G]:{0}", phone);
                return phone;                
            }

            public override string ToString()
            {
                return "From ToString();";
            }
        }
        class ModilePhoneFormatter : ICustomFormatter
        {
            string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider)
            {
                ModilePhone tmp = arg as ModilePhone;
                if (tmp == null) throw new ArgumentException(string.Format("ModilePhoneFormatter不支持{0}类型的",arg.GetType()));
                if (format == "NNN-NNNN-NNNN")
                    return string.Format("From ICustomFormatter:{0}{1}{2}-{3}{4}{5}{6}-{7}{8}{9}{10}", 
                                           tmp.phone[0], tmp.phone[1], tmp.phone[2],
                                           tmp.phone[3], tmp.phone[4], tmp.phone[5], tmp.phone[6],
                                           tmp.phone[7], tmp.phone[8], tmp.phone[9], tmp.phone[10]
                                        );
                return "";
            }
        }

        class ModilePhoneFormatProvider : IFormatProvider
        {
            object IFormatProvider.GetFormat(Type formatType)
            {
                if (formatType == typeof(ICustomFormatter))
                    return new ModilePhoneFormatter();
                else
                    return null;
            }
        }


  

下面是调用的例子:
           

     ModilePhone tmp = new ModilePhone();
     string str0 = string.Format(new ModilePhoneFormatProvider(), "{0:NNN-NNNN-NNNN}", tmp); 
     //str0 : From ICustomFormatter:151-1522-6678
     string str1 = string.Format("{0:G}", tmp);
     //str1 : From IFormattable[G]:15115226678
     string str2 = tmp.ToString();
     //str2 : //From ToString();
 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值