[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 ...
随机推荐
- Circle
Circle Memory Limit: 32768KB 64bit IO Format: %lld & %llu Status Description Your task is so ...
- easyui dialog 中嵌入html页面
最近使用easyui比较多,这个插件确实很好用.在使用时也遇到了大大小小的问题,好在都一一解决了. 记录一下今天遇到的问题. 目的:用easyui的dialog嵌入一个html页面(html中仍有要执 ...
- Windows下caffe的python接口配置
主要是因为,发现很多代码是用python编写的,在这里使用的python安装包是anaconda2. 对应下载地址为: https://www.continuum.io/downloads/ 安装py ...
- 【G彩娱乐网】作为一名程序员,我应该如何选购一台电脑?
G彩娱乐网说到程序员专用电脑,那肯定是苹果电脑.优点有很多,比如白平衡特别准.酷炫的黑科技.特别方便的软件等显而易见的优势:也有能够增加提案通过率.专注工作提高工作效率这样的玄学buff. 但是!并不 ...
- zabbix 3.2 高可用实现方式二-pacemaker+corosync实现zabbix高可用集群
一.pacemaker 是什么 1.pacemaker 简单说明 2.pacemaker 由来 二.pacemaker 特点 三.pacemaker 内部结构 1.群集组件说明: 2.功能概述 四.c ...
- Windows系统下python3中安装pyMysql
python2和python3是不兼容的,在py2中,链接数据库使用的是mysqldb,但在py3中是不能用的. 解决办法就是在py3中数据库使用的模块是pyMysql. 在dos窗口中安装第三方库会 ...
- .NEL IL实现对象深拷贝
对于深拷贝,通常的方法是将对象进行序列化,然后再反序化成为另一个对象.例如在stackoverflow上有这样的解决办法:https://stackoverflow.com/questions/785 ...
- 图片验证码的JAVA工具类
我们平时开发时经常会遇到需要图片验证码,基础的验证码包括了数字.字母.甚至可能有汉字.下面我给出一个简单的工具类. package com..ankang.tony.util; import java ...
- CentOS配置上网
CentOS设置: 进入CentOS命令模式: Centos7更改默认启动桌面(或命令行)模式 vi /etc/inittab:查看启动文件,在该文件中存在两种方式: multi-user.tar ...
- c#控件攻略宝典之ListBox控件
ListBox控件的使用: 1)控件属性 Items SelectedItems SelectioModes 2)数据绑定 DataSoure DisplayMember ValueMenber 3) ...