Information Technology Reference
In-Depth Information
#endregion
}
}
The GetFormat() method creates the object that implements the
ICustomFormatter interface. The ICustomFormatter.Format() method
does the actual work of formatting the output in the requested manner.
That one method translates the object into a string format. You can define
the format strings for ICustomFormatter.Format() so that you can spec-
ify multiple formats in one routine. The FormatProvider will be the
IFormatProvider object from the GetFormat() method.
To s p e c i f y y o u r c u s t o m f o r m a t , y o u n e e d t o e x p l i c i t l y c a l l s t r i n g . F o r m a t ( )
with the IFormatProvider object:
Console .WriteLine( string .Format( new CustomFormatter (),
"" , c1));
Yo u c a n c r e a t e I F o r m a t P r o v i d e r a n d I C u s t o m F o r m a t t e r i m p l e m e n t a t i o n s
for classes whether or not the class implemented the IFormattable inter-
face. So, even if the class author didn't provide reasonable ToString()
behavior, you can make your own. Of course, from outside the class, you
have access to only the public properties and data members to construct
your strings. Writing two classes, IFormatProvider and ICustomFormatter,
is a lot of work just to get text output. But implementing your specific text
output using this form means that it is supported everywhere in the .NET
Framework.
So now step back into the role of class author again. Overriding
Object.ToString() is the simplest way to provide a string representation of
your classes. You should provide that every time you create a type. It should
be the most obvious, most common representation of your type. It must
not be too verbose. It may end up in controls, HTML pages, or other
human-readable locations. On those rare occasions when your type is
expected to provide more sophisticated output, you should take advan-
tage of implementing the IFormattable interface. It provides the standard
way for users of your class to customize the text output for your type. If
you leave these out, your users are left with implementing custom for-
matters. Those solutions require more code, and because users are outside
of your class, they cannot examine the internal state of the object. But of
course, publishers cannot anticipate all potential formats.
 
Search WWH ::




Custom Search