C# IFormattable 这个接口怎么用的?
2个回答
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()));
}
}
}
}
{
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()));
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询