Recipe 3.2. Allowing a Type to Represent Itself as a String
Problem
Your class or structure needs to control how its information is displayed when its ToString method is called. In addition, you need to apply different formats to this information. For example, when creating a new data type, such as a Line class, you might want to allow objects of this type to be able to display themselves in a textual format. In the case of a Line object, it might display itself as (x1, y1)(x2, y2).
Solution
Override and/or implement the IFormattable.ToString method to display numeric information, such as for a Line structure:
- using System;
- using System.Text;
- using System.Text.RegularExpressions;
- public struct Line : IFormattable
- {
- public Line(int startX, int startY, int endX, int endY)
- {
- x1 = startX;
- x2 = endX;
- y1 = startY;
- y2 = endY;
- }
- public int x1;
- public int y1;
- public int x2;
- public int y2;
- public double GetDirectionInRadians( )
- {
- int xSide = x2 - x1;
- int ySide = y2 - y1;
- if (xSide == 0) // Prevent divide-by-zero.
- return (0);
- else
- return (Math.Atan (ySide / xSide));
- }
- public double GetMagnitude( )
- {
- int xSide = x2 - x1;
- int ySide = y2 - y1;
- return ( Math.Sqrt((xSide * xSide) + (ySide * ySide)));
- }
- // This overrides the Object.ToString method.
- // This override is not required for this recipe
- // and is included for completeness.
- public override string ToString( )
- {
- return (String.Format("({0},{1}) ({2},{3})", x1, y1, x2, y2));
- }
- public string ToString(string format)
- {
- return (this.ToString(format, null));
- }
- public string ToString(IFormatProvider formatProvider)
- {
- return (this.ToString(null, formatProvider));
- }
- public string ToString(string format, IFormatProvider formatProvider)
- {
- StringBuilder compositeStr = new StringBuilder("");
- if ((format != null) && (format.ToUpper( ).Equals("V")))
- {
- double direction = this.GetDirectionInRadians( );
- double magnitude = this.GetMagnitude( );
- string retStringD = direction.ToString("G5", formatProvider);
- string retStringM = magnitude.ToString("G5", formatProvider);
- compositeStr.Append("magnitude = ").Append(retStringM).Append
- ("\tDirection = ").Append(retStringD);
- }
- else
- {
- string retStringX1 = this.x1.ToString(format, formatProvider);
- string retStringY1 = this.y1.ToString(format, formatProvider);
- string retStringX2 = this.x2.ToString(format, formatProvider);
- string retStringY2 = this.y2.ToString(format, formatProvider);
- compositeStr.Append("(").Append(retStringX1).Append(",").Append
- (retStringY1).Append(")(").Append(retStringX2).Append
- (",").Append(retStringY2).Append(")");
- }
- return (compositeStr.ToString( ));
- }
- }
复制代码