简单的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 )
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 )
相关文章推荐
- erlang实现websocket简单示例
- Python简单实现socket信息发送与监听功能示例
- JAVAEE中用Session简单实现购物车功能示例代码
- jquery简单的拖动效果实现原理及示例
- 用SHA1或MD5 算法加密数据(示例:对用户身份验证的简单实现)
- C++简单实现对象引用计数示例(转)
- PHP简单实现欧拉函数Euler功能示例
- JS简单实现表格排序功能示例
- jQuery实现的两种简单弹窗效果示例
- Python实现简单的HttpServer服务器示例
- UEditor之实现配置简单的图片上传示例 转
- PyTorch上搭建简单神经网络实现回归和分类的示例
- JS实现的简单折叠展开动画效果示例
- Skinned Mesh原理解析和一个最简单的实现示例
- ASP+ADO实现数据读写简单示例
- 爬虫简单示例,用httpClient4.2.1实现(转载)
- XML 简单接口 (SAX2)用Visual Basic 实现的示例
- 贴下百度博客自动加好友的简单代码示例!!(c#.net实现)
- 以下截图简单说明娄氏理算规则引擎实现示例学习
- Skinned Mesh原理解析和一个最简单的实现示例