您的位置:首页 > 其它

简单的System.IFormattable实现示例:

2006-05-24 11:09 453 查看
实现System.IFormattable接口可以使用string.Format()方法按照不同的方式格式化自定义的类型,其实在使用Console.WriteLine("Cubic1: {0,15:XYZ}",a);方法,也只是先把Cubic1: {0,15:XYZ}字符串传递给string.Format()方法,格式化完毕后,送到控制台输出。
class Class1
{
static void Main(string[] args)
{
Cubic a = new Cubic(10,24,52);
//使用XYZ格式化字符串
Console.WriteLine("Cubic1: {0,15:XYZ}",a);
//使用16X格式化字符串
Console.WriteLine("Cubic1: {0,25:16X}",a);
//使用默认格式化字符串
Console.WriteLine("Cubic1: {0,15}",a);
//使用非法格式化字符串,其实还是默认格式化字符串
Console.WriteLine("Cubic1: {0,15:654}",a);
}
}

struct Cubic:System.IFormattable
{
int x,y,z;

public Cubic(int x,int y,int z)
{
this.z = z;
this.x = x;
this.y = y;
}
//这个方法是要实现System.IFormattable所必需的format就是格式化字符串
public string ToString(string format, IFormatProvider formatPorvider)
{
if(format == null)
return ToString();
switch( format )
{
case "XYZ":
return "X="+x.ToString()+" Y="+y.ToString()+" Z="+z.ToString();
case "16X":
return string.Format("x={0,-5:X},y={1,-5:X},z={2,-5:X}",x,y,z);
default:
return ToString();
}
}

public override string ToString()
{
return "( " + x.ToString() + " , " +y.ToString()+ " , " + z.ToString() + " )";
}
}

输出结果如下:
Cubic1: X=10 Y=24 Z=52
Cubic1: x=A ,y=18 ,z=34
Cubic1: ( 10 , 24 , 52 )
Cubic1: ( 10 , 24 , 52 )
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: