//前面那个本来想重新编辑的,但是那个编辑器之前被我调到Markdown之后,改回Tiny MCE编辑器不出来

1.ToString()方法 & IFormattable & IFormatProvider

先说ToString()

在System.Int32中定义了4个ToString方法

1.无参的ToString()是重写Object的,(or ValueType)的
2,3,4用法相同,第三个可以自定义Provider

IFormattable接口

int实现了IFormattable接口

IFormattable中只定义了一个ToString方法,format参数,和IFormatProvide类型的provider

IFormatProvider

在.NET中实现了IFormatProvider的类型,只有几个,其中包括SystemGlobalzation.CultureInfoIFormatProvider中定义了一个GetFormat方法(type),用来获取System.Globalization命名空间下的NumberFormatInfoDateTimeFormatInfo实例,
这两个类,同CultureInfo一样,也是IFormatProvider的实例,因为目前.NET中涉及国际化操作的,也就数字,和日期.NumberFormatInfo和DateTimeFormatInfo如果是获取关于日期,数字要格式化所需的东西.从DateTimeFormatInfo节选如下,还包括 中文,日语等等相关的内容

DateTimeFormatInfo,NumberFormatInfo是IFormatProvider实例,他们的GetFormat方法,根据参数type,返回this,或者null

实例:

 public static void Main()
{
int i = ; //ToString()
Console.WriteLine(i.ToString());//999 //ToString(format)
Console.WriteLine(i.ToString("x"));//hex 3e7
Console.WriteLine(i.ToString("X"));//Hex 3E7
Console.WriteLine(i.ToString("C"));//货币格式 ¥999.00 //ToString(format,provider)
//InvariantCulture无特定文化信息,999前面那符号是 国际通用货币符号
Console.WriteLine(i.ToString("C",System.Globalization.CultureInfo.InvariantCulture));//¤999.00
//en-US 语言-国家信息
Console.WriteLine(i.ToString("C",new System.Globalization.CultureInfo("en")));//$999.00 System.Console.ReadKey();
}

ToString(),ToString(format)实际都等同于调用ToString(format,provider)版本,
第一个参数为空时,默认为null或者"G"(一般情况下)
第二个惨参数为空,则根据System.Globalization.CultureInfo.CurrentCulture or System.Threading.Thread.CurrentThread.CurrentCulture来获取当前调用线程的区域文化信息

2.关于String.Fornat , StringBuilder.AppendFormat

String.Format(format,param object[] arg),例如String.Format("The Post with id equals {0:x4} is wiite on {1}",1,DateTime.Now)

Format方法在碰到{0}这样的标记时,会根据冒号后面的作为format,来调用arg的ToString(format);同时Format的重载允许传递一个自定义Provider

下面结合CLR via C#上的例子,来写一个自定义IFormatProvider

功能:将char类型按unicode输出,格式
u:小写的16进制格式
U:大写的16进制格式

结果显示为

代码为

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace CLR_String_Char
{
public class UnicodeFormatProvider : ICustomFormatter,IFormatProvider
{
public object GetFormat(Type formatType)
{
if(formatType == typeof(ICustomFormatter))
{
return this;
}
else
{
return System.Globalization.CultureInfo.CurrentCulture.GetFormat(formatType);
}
} public string Format(string format,object arg,IFormatProvider formatProvider)
{
var str = string.Empty;
if(arg.GetType() == typeof(char) &&
format != null
)//是char
{
if(format=="u")
{
str = "\\u" + ((int)((char)arg)).ToString("x4");
}
else if(format == "U")
{
str = "\\u" + ((int)((char)arg)).ToString("X4");
}
}
else if(arg is IFormattable)//arg 实现了IFormattable接口
{
//formatprovider
str = (arg as IFormattable).ToString(format,null);
}
else if(arg != null)
{
str = arg.ToString();
}
return str;
}
}
}

在上面代码中,昨天写的,今天想想漏掉一种情况,当arg是char类型,且format不为空,format又不等于'U'和'u'的情况下,返回String.Empty是错误的,应该交给常规情况来处理

重复代码很多,可以抽象出一个基类CustomerFormatter出来

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace CLR_String_Char
{
public abstract class CustomFormatter<T> : ICustomFormatter,IFormatProvider
{
//IFormatProvider.GetFormat
public object GetFormat(Type formatType)
{
if(formatType == typeof(ICustomFormatter))
{
//要的就是CustomFormatter
return this;
}
else
{
return System.Globalization.CultureInfo.CurrentCulture.GetFormat(formatType);
}
} //ICustomFormatter.Format
public string Format(string format,object arg,IFormatProvider formatProvider)
{
if(arg.GetType() == typeof(T) &&
format != null
)//是char
{
return FormatCustom(format,(T)arg);
}
return FormatRegular(format,arg);
} //处理常规字符
public string FormatRegular(string format,object arg)
{
if(arg is IFormattable)//arg 实现了IFormattable接口
{
//formatprovider
return (arg as IFormattable).ToString(format,null);
}
else if(arg != null)
{
return arg.ToString();
}
return string.Empty;
} //处理 自定义格式 类型,如果不重写,也返回FormatRegular
public virtual string FormatCustom(string format,T arg)
{
return FormatRegular(format,arg);
}
}
}

再次实现UnicodeFormatter时就简单多了,只需要继承自CustomFormatter<需要处理的类型>,再重写FormatCustom方法即可

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace CLR_String_Char
{
public class UnicodeFormatProvider : CustomFormatter<char>
{
//处理所有arg is T,format不为空的情况
public override string FormatCustom(string format,char arg)
{
if(format == "U")
{
return "\\u"+((int)arg).ToString("X4");
}
if(format == "u")
{
return "\\u"+((int)arg).ToString("x4");
} //是char,format不为空,交给FormatRegular来处理,如果不支持,抛出FormatException
return base.FormatCustom(format,arg);
}
}
}

练练手,简单的DatetimeFormat,zh-cn格式输出咱常用的yyyy-MM-dd HH:mm:ss形式

     class MyDateTimeFormatter : CustomFormatter<DateTime>
{
public override string FormatCustom(string format,DateTime arg)
{
//自定义了一个格式:zh-cn
if(format.Equals("zh-cn",StringComparison.OrdinalIgnoreCase))
{
return arg.ToString("yyyy-MM-dd HH:mm:ss");
}
return base.FormatCustom(format,arg);
}
}

关于Format的东西就到这里...午睡没了...啊

CLR via C# - Char_String - Format的更多相关文章

  1. CLR via C# - Char_String

    .NET中Char表示为16为的Unicode值,Char提供两个public const字段MinValue('\0',写成'\u0000'也是一样的)和MaxValue('\uffff'). Ch ...

  2. 【CLR via C#】CSC将源代码编译成托管模块

    下图展示了编译源代码文件的过程.如图所示,可用支持 CLR 的任何一种语言创建源代码文件.然后,用一个对应的编译器检查语法和分析源代码.无论选用哪一个编译器,结果都是一个托管模块(managedmod ...

  3. 使用用户自定义类型 CLR UDT

            一些复合类型进行范式分解是没有必要的,尤其是一些统一模型的情况下       SET NOCOUNT ON DECLARE @i TimeBalance SET @i = CAST(' ...

  4. 准备CLR源码阅读环境

    微软发布了CLR 2.0的源码,这个源码是可以直接在freebsd和windows环境下编译及运行的,请在微软shared source cli(http://www.microsoft.com/en ...

  5. CLR via C# 3rd - 03 - Shared Assemblies and Strongly Named Assemblies

    1. Weakly Named Assembly vs Strong Named Assembly        Weakly named assemblies and strongly named ...

  6. CLR via C# 3rd - 02 - Building, Packaging, Deploying, and Administering Applications and Types

    1. C# Compiler - CSC.exe            csc.exe /out:Program.exe /t:exe /r:MSCorLib.dll Program.cs       ...

  7. 【SQL】CLR聚合函数什么鬼

    之前写过一个合并字符串的CLR聚合函数,基本是照抄MS的示例,外加了一些处理,已经投入使用很长时间,没什么问题也就没怎么研究,近日想改造一下,遇到一些问题,遂捣鼓一番,有些心得,记录如下. 一.杂项 ...

  8. 提高你的数据库编程效率:Microsoft CLR Via Sql Server

    你还在为数据库编程而抓狂吗?那些恶心的脚本拼接,低效的脚本调试的日子将会与我们越来越远啦.现在我们能用支持.NET的语言来开发数据库中的对象,如:存储过程,函数,触发器,集合函数已及复杂的类型.看到这 ...

  9. CLR via C#学习笔记----知识总概括

    第1章 CLR的执行模型 托管模块的各个组成部分:PE32或PE32+头,CLR头,元数据,IL(中间语言)代码. 高级语言通常只公开了CLR的所有功能的一个子集.然而,IL汇编语言允许开发人员访问C ...

随机推荐

  1. RegexOptions.Compiled性能

    原文:http://www.cnblogs.com/me-sa/archive/2010/05/19/Is-RegexOptions-Compiled-a-Killer.html "使用正则 ...

  2. ORACLE触发器概述之【语句触发器】【weber出品】

    一.触发器概述 与表,视图,模式,或者数据库相关的PL/SQL过程,当触发条件被触发时,自动执行 分类: 1.语句触发器 2.行触发器 二.语句触发器 1. 什么是语句触发器 语句触发器,是指当执行D ...

  3. linux打开80端口及80端口占用解决办法

    linux打开80端口天客户那边有台服务器同一个局域网中都无法访问,排除lamp环境问题,发现时服务器中的防火墙没有开启80端口. 代码如下 复制代码vi /etc/sysconfig/iptable ...

  4. js页面加载进度条(这个就比较正式了,改改时间就完事儿)

    不废话,直接上代码 思路不难,就是一个animate方法配合随机数 duration内个三秒钟,是自定义的,可以改成页面加载时间,这样就完美了 <!doctype html> <ht ...

  5. js判断上传文件的类型和大小

    //检测文件大小和类型 function fileChange(target){ //检测上传文件的类型 if(!(/(?:jpg|gif|png|jpeg)$/i.test(target.value ...

  6. php json_encode数据格式化2种格式[]和{}

    在php中,json格式化数据后,会出现2种形式数据: 1.当array是一个从0开始的连续数组时,json_encode的结果是一个由[]括起来的字符串 $arr = array('a' , 'b' ...

  7. Lambda表达式 之 C#

    Lambda表达式 "Lambda表达式"是一个匿名函数,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量.它可以包含表达式和语句,并且可用于创建委托 ...

  8. The Suspects(POJ 1611 并查集)

    The Suspects Time Limit: 1000MS   Memory Limit: 20000K Total Submissions: 30158   Accepted: 14665 De ...

  9. linux安装xunsearch

    首先要确保ubuntu安装了gcc g++ make sudo apt-get install make gcc g++ 然后安装zlib,用来解压的: apt-get install zlib1g- ...

  10. Android 设置让EditText不自动获取焦点

    在EditText所在的父控件中设置如下属性: android:focusable="true" android:focusableInTouchMode="true&q ...