[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 ...
随机推荐
- AngularJS学习篇(十二)
AngularJS SQL ASP.NET 中执行 SQL 获取数据 <!DOCTYPE html> <html> <head> <meta charset= ...
- defer与async
defer:该属性指定的脚本不会修改DOM,因此代码可以安全的延迟执行. 含defer属性的script标签可以放在任何位置,在页面解析到该script标签时,开始下载脚本,但不会执行脚本,直至DOM ...
- js实现小球的弹性碰撞。
前 言 MYBG 小编最近在做自己的个人网站,其中就用到了一个小球碰撞检测的功能,想自己写,无奈本人能力不足啊(毕竟还是一个菜鸟)!!就想着找个插件用一下也好,可是找了好久也没有找到一个比较好用 ...
- DNA序列对齐问题
问题描述: 该问题在算法导论中引申自求解两个DNA序列相似度的问题. 可以从很多角度定义两个DNA序列的相似度,其中有一种定义方法就是通过序列对齐的方式来定义其相似度. 给定两个DNA序列A和B,对齐 ...
- 学会WCF之试错法——数据传输
数据传输 服务契约 [ServiceContract] public interface IService { [OperationContract] string GetData(int value ...
- HTML基础--position 绝对定位 相对定位 锚点链接
position 定位属性,检索对象的定位方式 一.语法:position:static /absolute/relative/fixed 取值: 1.static:默认值,无特殊定位,对象遵循HTM ...
- Django 入门案例开发(上)
Django 入门案例开发(中) http://www.cnblogs.com/focusBI/p/7858267.html Django是一个重量级的web开发框架,它提供了很多内部已开发好的插件供 ...
- Docker技术浅谈:私有化部署的优势以及在顶象内部的应用实践
顶象全景式业务安全风控体系基于新一代风控体系构建,并采用Docker技术进行私有云和公有云部署.本文主要和大家分享下Docker容器技术和顶象风控系统私有化部署的优势以及Docker容器技术在顶象内部 ...
- springboot-mybatis 批量insert
springboot mybatis 批量insert 操作 直接上代码: 1.首先要在pom.xml中导入包: 略...... 2.springboot mybatis配置: package com ...
- unity android相互调用
简介 有一些手机功能,Unity没有提供相应的接口,例如震动,例如不锁屏,例如GPS,例如... 有太多的特殊功能Unity都没有提供接口,这时候,我们就需要通过使用Android原生的ADT编辑器去 ...