Since ComplexNumber uses System.Double to represent its real
and imaginary parts, you can defer most of your work to the implementation of IFormattable
on System.Double. Assume that the ComplexNumber type will accept a format string exactly the
same way that System.Double does, and that each component of the complex number will be
output using this same format. Let??™s look at modifications to the ComplexNumber example to
support IFormattable:
Imports System
Imports System.Globalization
Public NotInheritable Class ComplexNumber
Implements IFormattable
Private ReadOnly real As Double
Private ReadOnly imaginary As Double
'Other methods removed for clarity.
Public Sub New(ByVal real As Double, ByVal imaginary As Double)
Me.real = real
Me.imaginary = imaginary
End Sub
Public Overrides Function ToString() As String
Return ToString("G", Nothing)
End Function
'IFormattable implementation
Public Overloads Function ToString(ByVal format As String, _
ByVal formatProvider As IFormatProvider) As String _
Implements IFormattable.ToString
Dim result As String = "(" & real.ToString(format, formatProvider) & _
" " & real.ToString(format, formatProvider) & ")"
Return result
End Function
End Class
CHAPTER 14 n VB 2008 BEST PRACTICES 328
Public NotInheritable Class EntryPoint
Shared Sub Main()
Dim num1 As ComplexNumber = New ComplexNumber(1.
Pages:
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533