[C#]使用IFormattable接口来实现字符串格式化
本文为原创文章、源代码为原创代码,如转载/复制,请在网页/代码处明显位置标明原文名称、作者及网址,谢谢!
开发工具:VS2017
语言:C#
DotNet版本:.Net FrameWork 4.0及以上
一、编写一个Person类,代码如下:
class Person
{
public string FirstName { set; get; }
public string LastName { set; get; }
}
并让Person类继承IFormattable,代码如下:
class Person:IFormattable
{
public string FirstName { set; get; }
public string LastName { set; get; } public string ToString(string format, IFormatProvider formatProvider)
{
//关键代码,后面给出
}
}
这里将会列出需要实现IFormattable的方法ToString(string format, IFormatProvider formatProvider),这里是关键代码,用来格式字符串,暂时不给出,由后面给出。
二、编写 PersonFormatter类,让其继承IFormatProvider及ICustomFormatter,用于对字符串进行格式化,代码如下:
class PersonFormatter : IFormatProvider,ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
//Format实现代码
} public object GetFormat(Type formatType)
{
//GetFormat实现代码
}
}
Format:用于格式化字符串
Format的实现代码如下:
Person person = arg as Person;
switch(format)
{
case "CH":return $"{person.LastName} {person.FirstName}";
case "EN":return $"{person.FirstName} {person.LastName}";
default: return $"{person.LastName} {person.FirstName}";
}
GetFormat的实现代码如下:
if (formatType == typeof(ICustomFormatter)) return this;
return null;
因此,PersonFormatter类的代码如下:
class PersonFormatter : IFormatProvider,ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
Person person = arg as Person;
switch(format)
{
case "CH":return $"{person.LastName} {person.FirstName}";
case "EN":return $"{person.FirstName} {person.LastName}";
default: return $"{person.LastName} {person.FirstName}";
}
} public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
}
三、实现Person类IFormattable接口ToString方法,代码如下:
ICustomFormatter customFormatter = formatProvider as ICustomFormatter;
if (customFormatter == null) return this.ToString();
return customFormatter.Format(format, this, null);
最终Person类代码如下:
class Person:IFormattable
{
public string FirstName { set; get; }
public string LastName { set; get; } public string ToString(string format, IFormatProvider formatProvider)
{
ICustomFormatter customFormatter = formatProvider as ICustomFormatter;
if (customFormatter == null) return this.ToString();
return customFormatter.Format(format, this, null);
}
}
四、使用Peson类的ToString方法,编写以下代码:
Person p1 = new Person { FirstName = "XY", LastName = "CN" };
PersonFormatter pf = new PersonFormatter();
string s1 = p1.ToString("CN", pf);
Console.WriteLine(s1);
string s2 = p1.ToString("EN", pf);
Console.WriteLine(s2);
五、运行结果:

六、附上完整源码:
class Program
{
static void Main(string[] args)
{
Person p1 = new Person { FirstName = "XY", LastName = "CN" };
PersonFormatter pf = new PersonFormatter();
string s1 = p1.ToString("CN", pf);
Console.WriteLine(s1);
string s2 = p1.ToString("EN", pf);
Console.WriteLine(s2);
}
} class PersonFormatter : IFormatProvider,ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
Person person = arg as Person;
switch(format)
{
case "CH":return $"{person.LastName} {person.FirstName}";
case "EN":return $"{person.FirstName} {person.LastName}";
default: return $"{person.LastName} {person.FirstName}";
}
} public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
} class Person:IFormattable
{
public string FirstName { set; get; }
public string LastName { set; get; } public string ToString(string format, IFormatProvider formatProvider)
{
ICustomFormatter customFormatter = formatProvider as ICustomFormatter;
if (customFormatter == null) return this.ToString();
return customFormatter.Format(format, this, null);
}
}
[C#]使用IFormattable接口来实现字符串格式化的更多相关文章
- C# 自定义类型通过实现IFormattable接口,来输出指定的格式和语言文化的字符串(例:DateTime)
常规的调用ToString()方法,存在两个问题. (1).调用者无法控制字符串的格式 (2).调用者不能方便的选择一种特定的语言文化来格式化字符串. 在开发一些国际化的应用时,应用程序需要调用与当前 ...
- 【C# IO 操作 】IFormatProvider接口|IFormattable 接口 格式化接口
IFormatProvider接口获取一个满足要求的个格式化器. 方法 object? GetFormat(Type? formatType);GetFormat方法主要提供一个满足指定要求的对象,该 ...
- 利用IFormattable接口自动参数化Sql语句
提要 string.Format("{0},{1}",a,b)的用法大家都不陌生了,在很多项目中都会发现很多sql语句存在这样拼接的问题,这种做法很多"懒"程序 ...
- Java 字符串格式化详解
Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...
- python-学习笔记之-Day5 双层装饰器 字符串格式化 python模块 递归 生成器 迭代器 序列化
1.双层装饰器 #!/usr/bin/env python # -*- coding: utf-8 -*- # author:zml LOGIN_INFO = False IS_ADMIN = Fal ...
- Python_Day_5装饰器、字符串格式化、序列化、内置模块、生成器、迭代器之篇
一.装饰器 为什么要用装饰器??? 在实际的开发环境中应遵循开发封闭原则,虽然在这个原则是用的面向对象开发,但也适用于函数式编程,简单地说,它规定已经实现的功能代码不是允许修改的,但是可以被扩展: 封 ...
- python的三种字符串格式化方法
1.最方便的 print 'hello %s and %s' % ('df', 'another df') 但是,有时候,我们有很多的参数要进行格式化,这个时候,一个一个一一对应就有点麻烦了,于是就有 ...
- python- 双层装饰器 字符串格式化 python模块 递归 生成器 迭代器 序列化
1.双层装饰器 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # author:zml LOGIN_INFO = False IS_ADMIN = Fa ...
- PYDay10&11&12&13-常用模块:time|datetime|os|sys|pickle|json|xml|shutil|logging|paramiko、configparser、字符串格式化、py自动全局变量、生成器迭代器
1.py文件自动创建的全局变量 print(vars()) 返回值:{'__name__': '__main__', '__package__': None, '__loader__': <_f ...
随机推荐
- 剖析Linux系统调用的执行路径
在什么是操作系统这篇文章中,介绍过操作系统像是一个代理一样,为我们去管理计算机的众多硬件,我们需要计算机的一些计算服务.数据管理的服务,都由操作系统提供接口来完成.这样做的好处是让一般的计算机使用者不 ...
- Oracle-3 - :超级适合初学者的入门级笔记--用户权限,set运算符,高级子查询
上一篇的内容在这里第二篇内容, 用户权限:创建用户,创建角色,使用grant 和 revoke 语句赋予和回收权限,创建数据库联接 创建用户:create user xxx identified b ...
- Docker简介和安装
1.Docker 和传统虚拟化方式的不同之处 传统虚拟机技术是虚拟出一套硬件后,在其上运行一个完整操作系统,在该系统上再运行所需应用进程: 而容器内的应用进程直接运行于宿主的内核,容器内没有自己的内核 ...
- angualr4 路由 总结笔记
使用cli命令创建根路由模块 ng g cl app.router 或自己建一个路由配置文件 如:app/app.router.ts // app/app.router.ts // 将文件修改为 im ...
- javaScript函数提升及作用域
代码片段: var a = 1; function foo() { console.log(a); //输出为undefined if (!a) { var a = 2; } alert(a); }; ...
- .net表达式计算器(中缀表达式转后缀表达式,支持20多个数学函数,支持函数嵌套)
最近在网上查了一下表达工计算器的类库,发现Java版本的有一个比较成熟的叫W3EVal,好像是一个IBM工程师写的,.net就很少了(可能是我了解不够多),但投机取巧的实现思路有很多,比如: (1)将 ...
- Spring MVC体系结构和处理请求控制器
Spring MVC体系结构和处理请求控制器 一:MVC设计模式: (1.)数据访问接口:DAO层 (2.)处理业务逻辑层:Service层 (3.)数据实体:POJO (4.)负责前段请求接受并处理 ...
- [转载] 详细讲解Hadoop中的简单数据库HBase
转载自http://www.csdn.net/article/2010-11-28/282614 数据模型 HBase数据库使用了和Bigtable非常相似的数据模型.用户在表格里存储许多数据行.每个 ...
- python基础-------函数(三)
迭代器 一.迭代的概念 迭代:1 重复2 下一次重复是基于上一次的结果 l=['a','b','c','d'] count=0while count < len(l): print(l[coun ...
- python基础-------函数(一)
一 为何要有函数?不加区分地将所有功能的代码垒到一起, 问题是: 代码可读性差 代码冗余 代码可扩展差 如何解决?函数即工具,事先准备工具的过程是定义函数,拿来就用指的就是函数调用 结论:函数使用必须 ...