实现自定义IFormattable

using System;

using System.Collections;

using System.Linq;

using System.Text;

using System.Collections.Generic;

using System.Runtime.Serialization;





namespace TestCS

{

    //实现IFormattable

    struct Vector:IFormattable

    {

        public double x, y, z;



        public Vector(double a, double b, double c)

        {

            x = a; y = b; z = c;

        }



        #region IFormattable 成员



        public string ToString(string format, IFormatProvider formatProvider)

        {

            switch (format.ToUpper())

            {

                case "N": return "||" + Norm().ToString() + "||";

                case "VE": return string.Format("{0:E},{1:E},{2:E}", x, y, z);

                case "IJK":

                    StringBuilder sb = new StringBuilder(x.ToString(), 30);

                    sb.AppendFormat(" i + ");

                    sb.AppendFormat(y.ToString());

                    sb.AppendFormat(" j + ");

                    sb.AppendFormat(z.ToString());

                    sb.AppendFormat(" k");

                    return sb.ToString();

                default:

                    return ToString();

            }

            

        }



        private double  Norm()

        {

            return x * x + y * y + z * z;

        }



        #endregion

    }





    public class Progarm

    {

        public static void Main(string[] args)

        {

            //IFormatProvider表示要显示的变量

            Vector v1 = new Vector(2.3, 44.24, -33.3);

            Console.WriteLine("{0:N}", v1);

            Console.WriteLine("{0:ve}", v1);

            Console.WriteLine("{0:ijk}", v1);



            Console.ReadLine();

        }

    }





  

}

你可能感兴趣的:(C++,c,C#,J#,LINQ)