C# IFormattable 这个接口怎么用的?

如题所述

第1个回答  2013-04-12
提供一个指定的格式化类,并且使用该类进行对数据的格式化。【示例,指定总共长度,如果不满足使用×填满】namespace nibian
{

public class A:IFormattable
{
public long Number { get; set; } public string ToString(string format, IFormatProvider formatProvider)
{
return ((ICustomFormatter)formatProvider).Format(format, Number, formatProvider);
} //覆盖父类的ToString方法
public override string ToString()
{
return null;
}
} public class MyFormat:IFormatProvider,ICustomFormatter
{
private const int width = 5; //总共5位数长度
public object GetFormat(Type formatType)
{
return this;
} public string Format(string format, object arg, IFormatProvider formatProvider)
{
string result = arg.ToString();
try
{
int blank=0;
blank = int.Parse(format); if (blank < 0)
{
result = result.PadLeft(-blank, '×'); //左边补上若干×
}
else if (blank > 0)
{
result = result.PadRight(blank, '×'); //右边补上若干×
}
}
catch (Exception)
{
result = null;
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
for (long i = 1; i < 100000; i *= 10)
{
a.Number = i;
Console.WriteLine(a.ToString("-5", new MyFormat()));
}
}
}
}
第2个回答  2013-04-12
我也知道这个 问题 求解答