简单的System.IFormattable实现示例:

实现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 )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值