点滴拾遗 - 自定义 Format 控制 String.Format 行为
2024-10-21 06:42:02
String.Format 一重载方法的签名如下
public static string Format(
IFormatProvider provider,
string format,
params Object[] args
)
可以通过自定义 IFormatProvider 接口来控制 String.Format 执行过程中的特定行为。
过程如下
1, 自定义类实现 IFormatProvider 接口(object GetFormat 方法)
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
2, 实现 ICustomFormatter 借口(string Format 方法)
摘自 MSDN。功能为控制 Int64 type 的string输出。
public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
// Provide default formatting if arg is not an Int64.
if (arg.GetType() != typeof(Int64))
try
{
return HandleOtherFormats(fmt, arg);
}
catch (FormatException e)
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
} // Provide default formatting for unsupported format strings.
string ufmt = fmt.ToUpper(CultureInfo.InvariantCulture);
if (!(ufmt == "H" || ufmt == "I"))
try
{
return HandleOtherFormats(fmt, arg);
}
catch (FormatException e)
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
} // Convert argument to a string.
string result = arg.ToString(); // If account number is less than 12 characters, pad with leading zeroes.
if (result.Length < ACCT_LENGTH)
result = result.PadLeft(ACCT_LENGTH, '');
// If account number is more than 12 characters, truncate to 12 characters.
if (result.Length > ACCT_LENGTH)
result = result.Substring(, ACCT_LENGTH); if (ufmt == "I") // Integer-only format.
return result;
// Add hyphens for H format specifier.
else // Hyphenated format.
return result.Substring(, ) + "-" + result.Substring(, ) + "-" + result.Substring();
}
使用实现好的 Format 类
long acctNumber;
double balance;
DaysOfWeek wday;
string output; acctNumber = ;
balance = 16.34;
wday = DaysOfWeek.Monday; output = String.Format((new AcctNumberFormat(),
"On {2}, the balance of account {0:H} was {1:C2}.",
acctNumber, balance, wday);
Console.WriteLine(output);
执行结果如下
参考资料
Culture invariant Decimal.TryParse() http://stackoverflow.com/questions/23131414/culture-invariant-decimal-tryparse
What does IFormatProvider do? http://stackoverflow.com/questions/506676/what-does-iformatprovider-do
IFormatProvider Interface https://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx
最新文章
- war项目在tomcat上面部署
- linux小技巧
- word20161207
- 访问 IIS 元数据库失败 的解决方法
- percent-encode 百分号编码
- weblogic启动报错之未修改hosts产生错误
- 简单使用JSON,通过JSON 字符串来创建对象(二)
- SVG文本
- 机器学习算法--Perceptron(感知机)算法
- Spinner控件详解
- PGM:概率论基础知识
- 为什么移动构造要使用noexcept
- 列式数据库~clickhouse日常管理
- javascript五种基本类型
- java集合类整理
- C++ template —— 类型区分(十一)
- vue--非父子组件之间的传值
- 何时使用[self release]
- Vue 备
- MySQL的一些常用sql函数(持续更新。。)