[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 ...
随机推荐
- Android 开发笔记___SD卡基本操作
package com.example.alimjan.hello_world; /** * Created by alimjan on 7/5/2017. */ import android.ann ...
- 还原NuGet程序包
官网:https://msdn.microsoft.com/zh-cn/magazine/hh547106.aspx 在获取团队中的项目或者下载他人的项目Demo后,运行项目有时会提示某些dll找不到 ...
- 引入CSS的方式有哪些?link和@import的有何区别应如何选择【转载】
看到淘宝网页中这样写使用的是import,而很多网站都是使用link,当然还有一些页面比较简单,流量很大的网站,是直接将CSS写在html代码中的?他们有什么区别?CSS用import还是link好? ...
- 状态码为 200 from cache和304 Not modified的区别
1.请求状态码为 200 from cache: 表示该资源已经被缓存过,并且在有效期内,所以不再向浏览器发出请求,直接使用本地缓存. 如下图: 2.状态码为 304 Not modified: 表 ...
- cocos2d导入iOS原生项目
最近公司最新发下任务让融合一个cocos2dx写的游戏项目融合进现有项目,当看到要求时内心瞬间无数羊驼奔腾.------ 虽说内心是拒绝的,但是任务已经派发就必须要完成啊.所以在网上搜了大量的融入教程 ...
- jquery多种方式实现输入框input输入时的onput,onpropertychange,onchange触发事件及区别
有关inputs输入内容的事件监听,一般我们会想到下面几个关键词:onput,onpropertychange,onchange onput与onchange的一个区分 onput:该事件在 < ...
- java输出各种学生成绩
class stu { public String stuno; public String name; public float math; public float english; public ...
- STM32F4中USB与PC双向通信
STM32F4系列处理器内部集成了USB-OTG控制器,在不要外部USB IC下就可以实现USB通信,最近两天看了下如何利用STM32的USB实现通信,记录下关键步骤: 1. 从http://www. ...
- Struts2初探
我记得美妙的瞬间:在我的面前出现了你,有如昙花一现的幻影 今天写一篇Struts2框架的,在很久很久以前,Struts2可谓是称霸江湖,纵然现在有后起之秀,但Struts2依然可以成为老牌的主流框架, ...
- 用JAVA中BufferedImage画出漂亮的验证码点击变化
如果我们想用JAVA中BufferedImage画出漂亮的验证码点击变化怎么实现呢,类似这样: 点击变化,以下是实现过程,直接上代码: 首先前台:<i><img style=&quo ...