Information Technology Reference
In-Depth Information
whose names are longer than 20 characters, and you want to modify the
format to provide a 50-character width for the customer name. That's why
the IFormatProvider interface is there. You create a class that implements
IFormatProvider and a companion class that implements ICustomFormatter
to create your custom output formats. The IFormatProvider interface
defines one method: GetFormat(). GetFormat() returns an object that
implements the ICustomFormatter interface. The ICustomFormatter inter-
face specifies the method that does the actual formatting. The following
pair creates modified output that uses 50 columns for the customer name:
// Example IFormatProvider:
public class
CustomFormatter
:
IFormatProvider
{
#region
IFormatProvider Members
// IFormatProvider contains one method.
// This method returns an object that
// formats using the requested interface.
// Typically, only the ICustomFormatter
// is implemented
public object
GetFormat(
Type
formatType)
{
if
(formatType ==
typeof
(
ICustomFormatter
))
return new
CustomerFormatProvider
();
return null
;
}
#endregion
// Nested class to provide the
// custom formatting for the Customer class.
private class
CustomerFormatProvider
:
ICustomFormatter
{
#region
ICustomFormatter Members
public string
Format(
string
format,
object
arg,
IFormatProvider
formatProvider)
{
Customer
c = arg as
Customer
;
if
(c ==
null
)
return
arg.ToString();
return string
.Format(
"{0,50}, {1,15}, {2,10:C}"
,
c.Name, c.ContactPhone, c.Revenue);
}