這是我現在已經使用了很長時間的風格,而且運作良好:通過使用
public struct Point3D : IFormattable
{
public static string DefaultFormat = "F3";
public float x,y,z;
public string ToString(string format, IFormatProvider formatProvider)
{
string fmt = "({0:#},{1:#},{2:#})".Replace("#", format);
return string.Format(formatProvider, fmt, x, y, z);
}
public string ToString(string format)
{
return ToString(format, null);
}
public override string ToString()
{
return ToString(DefaultFormat);
}
}
static void Main(string[] args)
{
Point3D A = new Point3D() { x = (float)Math.PI, y = (float)(-4/Math.PI), z = (float)(0.005 * Math.PI) };
Debug.WriteLine(A.ToString());
Debug.WriteLine(A.ToString("F2"));
}
打印出以下
(3.142,-1.273,0.016)
(3.14,-1.27,0.02)
這正是我想避免的。如果我每次想要打印一個點時最終都明確地實現它,那麼爲Point3D使用ToString()會有什麼意義? – Dina 2012-03-15 10:58:44