C#自定义格式化string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FormattableString
{
    class Program
    {
        static void Main(string[] args)
        {
            double d = 13.45;
            int i = 45;
            Console.WriteLine();
            Console.WriteLine("The double is{0,6:F} and the int contains {1}", d, i);

            Vector vc = new Vector();
            vc.x = 1;
            vc.y = 2;
            vc.z = 3;
            Console.WriteLine("{0:N}", vc);
            Console.ReadKey();
        }
    }

    public class Vector : IFormattable
    {
        public double x, y, z;

        string IFormattable.ToString(string format, IFormatProvider formatProvider)
        {
            if (format == null)
            {
                return ToString();
            }
            string formatUpper = format.ToUpper();
            switch (formatUpper)
            {
                case "N":
                    return "||" + Norm() + "||";
                default:
                    return ToString();

            }
            throw new NotImplementedException();
        }
        public double Norm()
        {
            return x * x + y * y + z * z;
        }
    }
}

 

posted on 2013-03-19 22:50  R.Ray  阅读(246)  评论(0)    收藏  举报

导航