首页 > 代码库 > 自定义格式化字符串
自定义格式化字符串
1 public class Vector : IFormattable 2 { 3 public double X { get; set; } 4 public double Y { get; set; } 5 public double Z { get; set; } 6 7 public double Norm() 8 { 9 return X * X + Y * Y + Z * Z;10 }11 12 public override string ToString()13 {14 return "(" + X + "," + Y + "," + Z + ")";15 }16 17 public string ToString(string format, IFormatProvider formatProvider)18 {19 if (format == null)20 {21 return ToString();22 }23 24 string formatUpper = format.ToUpper();25 26 switch (formatUpper)27 {28 case "N":29 return "|| " + Norm().ToString() + " ||";30 case "VE":31 return string.Format("({0:E},{1:E},{2:E})", X, Y, Z);32 case "IJK":33 var sb = new StringBuilder(X.ToString(), 30);34 sb.AppendFormat(" i + ");35 sb.AppendFormat(Y.ToString());36 sb.AppendFormat(" j + ");37 sb.AppendFormat(Z.ToString());38 sb.AppendFormat(" k");39 return sb.ToString();40 default:41 return ToString();42 }43 }44 }
1 static void Main(string[] args)2 {3 Vector vector1 = new Vector { X = 3, Y = 4, Z = 5 };4 Vector vector2 = new Vector { X = 5, Y = 4, Z = 3 };5 Console.WriteLine("In IJK format, v1 is {0,10:IJK},V2 is {1,10:IJK}", vector1, vector2);6 7 8 Console.ReadKey();9 }
自定义格式化字符串
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。