美文网首页
String Format

String Format

作者: 若水生花啊啊啊 | 来源:发表于2017-12-28 23:22 被阅读0次
    class Program
        {
            static void Main(string[] args)
            {
                Vector v1 = new Vector(1, 32, 5);
                Vector v2 = new Vector(845.4,54.3,-7.8);
                Console.WriteLine("\nIn IJK format,\nv1 is {0,30:IJK}\nv2 is {1,30:IJK}", v1, v2);
                Console.WriteLine("\nIn default format,\nv1 is {0,30}\nv2 is {1,30}", v1, v2);
                Console.WriteLine("\nIn VE format,\nv1 is {0,30:VE}\nv2 is {1,30:VE}", v1, v2);
                Console.WriteLine("\nNorms are:\nv1 is {0,20:N}\nv2 is {1,30:N}", v1, v2);
    
                Console.ReadKey();
            }
        }
    
        struct Vector : IFormattable
        {
            public double x, y, z;
    
            public Vector(double x, double y, double z)
            {
                this.x = x;
                this.y = y;
                this.z = z;
            }
    
            public string ToString(String format, IFormatProvider formatProvider)
            {
                if (format == null)
                {
                    return ToString();
                }
    
                string formatUpper = format.ToUpper();
                switch (formatUpper)
                {
                    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();
                }
            }
    
            public override string ToString()
            {
                return "( " + x + ", " + y + ", " + z + " )";
            }
    
            public double Norm()
            {
                return x * x + y * y + z * z;
            }
        }
    

    {0,30:IJK}中IJK会当成参数传给ToString中的format。这已经验证过,可是为什么不可以写成 {0,:IJK}这样?
    格式不是这样吗?{index[,alignment][:formatString]} 。
    😚😚😚

    相关文章

      网友评论

          本文标题:String Format

          本文链接:https://www.haomeiwen.com/subject/otubgxtx.html