//前面那个本来想重新编辑的,但是那个编辑器之前被我调到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. javascript紧接上一张for循环的问题,我自己的理解

    这类问题,通常都是在for循环里,根据i的变化作为dom的下标来作当前dom的点击事件, 预期是,每个点击事件都对应相应的i下标,但是问题是,每次点击的都是最后一次节点的dom. 原因就是其实我们作点 ...

  2. Linq中的多表左联,详细语句

    from m in context.WX_MemberCollectDish join d in context.Dish on m.DishID equals d.DishID into temp ...

  3. C#操作Flash动画

    对于在C#开发的过程中没有接触过Flash相关开发的人员来说,没有系统的资料进行学习,那么这篇文档针对于初学者来说是很好的学习DEMO. 本文章中的DEMO实现了C#的COM控件库中本来就带有对fla ...

  4. OpenGL ES 2.0 光照

    基本的光照 光照分成了3种组成元素(3个通道):环境光.散射光以及镜面光. 材质的反射系数实际指的就是物体被照射处的颜色,散射光强度指的是散射光中的RGB(红.绿.蓝)3个色彩通道的强度. 环境光 指 ...

  5. C/C++中的空类及抽象类大小

    代码: #include <iostream> using namespace std; struct A{ }; struct B{ int i; }; class C:B{ ; }; ...

  6. maven项目依赖被改为文件夹时如何改回lib

    如图

  7. Lua绑定C++类

    原文:http://blog.csdn.net/chenee543216/article/details/12074771 以下是代码: Animal.h文件 #pragma once #ifndef ...

  8. LeetCode_Triangle

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  9. LeetCode_Sort Colors

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  10. Common Words

    Common Words Let's continue examining words. You are given two string with words separated by commas ...