//前面那个本来想重新编辑的,但是那个编辑器之前被我调到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. dataset导出成excel

    之前网上查找了很多关于这类的代码.要不是中文乱码,要不是就是太复杂.这个是我用过最好用的. //ds为数据源,filename为保存的文件名 publicvoidCreateExcel(DataSet ...

  2. 返回ipv 地址

    //返回ipv 地址 public static string GetIP4Address() { string IP4Address = String.Empty; foreach (IPAddre ...

  3. AngularJs练习Demo10 ngInclude

    @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport&quo ...

  4. OpenGL ES 2.0 纹理映射

    纹理坐标用符点数表示,范围一般从0.0到1.0,在纹理坐标系中.纹理坐标系原点在左上侧,向右为S轴,向下为T轴.两个轴的取值范围都是0.0-1.0. 纹理映射 纹理映射:把一幅纹理图应用到相应的几何图 ...

  5. hdu 1215 七夕节

    Problem Description 七夕节那天,月老来到数字王国,他在城门上贴了一张告示,并且和数字王国的人们说:"你们想知道你们的另一半是谁吗?那就按照告示上的方法去找吧!" ...

  6. K60的DMA多路脉冲计数

    最近在做飞思卡尔的智能车,由于要用到两路脉冲计数,但是由于K60只有3个FTM, 一个分给电机,一个分给舵机,另一个用于正交解码. 所以FTM用不到了,只能另行办法.LPT虽然也可以计数,但是却只能计 ...

  7. Ajax中send方法参数的使用

    一般情况下,使用Ajax提交的参数多是些简单的字符串,可以直接使用GET方法将要提交的参数写到open方法的url参数中,此时send方法的参数为null. 例如 : var url = " ...

  8. #能力开放平台系列-Fiddler访问Rest服务

    问题 最近开发能力开放平台,需要将Dubbo服务转换成Rest服务,虽然转换很成功(后续文档会写出如何将Dubbo服务转换成Rest接口),但是调试起来特别的麻烦. 解决方案: Fiddler解决方案 ...

  9. Swift UI

    概述 Apple近日发布了Swift编程语言,Swift是供iOS和OS X应用编程的新编程语言.相信很多开发者都在学习这门新语言.   废话不多说,下面我就来学习使用Swift创建一个简单的UI应用 ...

  10. C语言读写伯克利DB 4

    因为缓存数据的buffer总是不够大(会引起段错误)索性从堆上拿了两块大内存 /* 功能说明:逐日存储来访用户(使用伯克利DB) 根据存储的用户信息确定某用户是否是首次来访用户(未被存储的伯克利DB) ...