小牛电子书 > 其他电子书 > VB2008从入门到精通(PDF格式英文版) >

第109章

VB2008从入门到精通(PDF格式英文版)-第109章

小说: VB2008从入门到精通(PDF格式英文版) 字数: 每页3500字

按键盘上方向键 ← 或 → 可快速上下翻页,按键盘上的 Enter 键可回到本书目录页,按键盘上方向键 ↑ 可回到本页顶部!
————未阅读完?加入书签已便下次继续阅读!





…………………………………………………………Page 327……………………………………………………………

                                                      CH AP T E R   1 1   ■    L E A R N IN G   AB O U T   。 N E T  G E N E R I CS 305 



Public Interface IWorksheetSerialize 

    Sub AssignCellState(Of ValueType)(ByVal row As Integer; _ 

      ByVal col As Integer; ByVal value As ValueType) 



    Sub AssignCellState(ByVal row As Integer; ByVal col As Integer; _ 

                               ByVal value As Object) 

End Interface 



     The problem is that the function passes in as a parameter of one type and is assigned  

to CellState; which is another undefined  generics type。 The implementation of the  

AssignCellState() method is as follows: 



Public Sub AssignCellState(ByVal row As Integer; ByVal col As Integer; _ 

  ByVal value As Object) Implements IWorksheetSerialize。AssignCellState 

    CellState(row; col) = DirectCast(value; BaseType) 

End Sub 



     The code looks so simple and innocent; but it is actually masking many potential problems。  

Here; the value of the parameter value is of type Object。 Then to convert the value to type  

BaseType—because that is what CellState is defined to be—you use a cast。 For the most part;  

this code will work; if value is the correct type。 

     Consider the following code; which would generate an exception。 



Dim worksheet As Worksheet(Of Double) = New Worksheet(Of Double)() 

worksheet。Dimension(10; 10)Dim buffer As String = 〃hello; world〃 

worksheet。AssignCellState(1; 2; buffer) 



     The variable worksheet is declared to be of type Worksheet(Of Double)。 When the method  

AssignCellState() is called; the cell 1; 2 is assigned to be type String。 Calling AssignCellState() is  

not a problem; but in the implementation; the assignment will fail。 You can’t willy…nilly assign  

a String to a Double。 Of course; this begs the question; “Why have a function of type Object?”  

Sometimes you can’t get around it; and you need to write a general object method。 The proper  

way to call the method would be as follows: 



Dim worksheet As Worksheet(Of Double) = New Worksheet(Of Double)() 

worksheet。Dimension(10; 10) 

Dim buffer As String = 〃hello; world〃 

worksheet。AssignCellState(1; 2; Double。Parse(buffer)) 



     The bolded code shows that the string buffer is parsed by the Double。Parse() method;  

converting a string buffer into a Double value。 Of course; the conversion will fail; since the string  

buffer represents a string; but that is another problem。 

     Another way of solving the problem is to avoid the object altogether and declare the method  

as being a  generics method。 The advantage of the  generics method is that you could  

execute in a type…safe manner without explicitly forcing the user to implement parsing routines。  

Consider the following modified  generics method declaration of AssignCellState()。 


…………………………………………………………Page 328……………………………………………………………

306       CH AP T E R   1 1   ■    L E A R N I N G   A B OU T   。 N E T  G E N E R I CS 



           Public Sub AssignCellState(Of ValueType)(ByVal row As Integer; _ 

                                                   ByVal col As Integer; _ 

                                                   ByVal value As ValueType) _ 

            Implements IWorksheetSerialize。AssignCellState 

              If GetType(BaseType)。IsAssignableFrom(GetType(ValueType)) Then 

                  CellState(row; col) = DirectCast(DirectCast(value; Object); BaseType) 

              ElseIf TypeOf (value) Is String And _ 

                     GetType(Double)。IsAssignableFrom(GetType(BaseType)) Then 

                  Dim obj As Object = DirectCast(value; Object) 

                  Dim dValue As Double = Double。Parse(CStr(obj)) 

                  Dim objDValue As Object = CType(dValue; Object) 

                  CellState(row; col) = DirectCast(objDValue; BaseType) 

              Else 

                  Throw New InvalidCastException(〃Could not perform conversion〃) 

              End If 

           End Sub 



                The cell state to be assigned is a  generics parameter and defined to be the type ValueType。  

          You can only guess what ValueType is; it is determined when the method AssignCellState(Of )()  

          is called。 For example; suppose this method call is made: 



          Dim buffer As String = 〃hello; world〃 

          worksheet。AssignCellState(1; 2; buffer) 



                The type for ValueType will be String; even though you have not explicitly specified it。 One  

          of the things that is possible with  generics methods is that types can be deduced implic

          itly。 The following would be an explicit usage of AssignCellState(Of )()。 



          Dim buffer As String = 〃hello; world〃 

          worksheet。AssignCellState(Of String)(1; 2; buffer) 



                Knowing that ValueType is String; AssignCellState(Of )() will then first check if  

          ValueType can be assigned to  BaseType: 



           If GetType(BaseType)。IsAssignableFrom(GetType(ValueType)) Then 



                This code is rather clever; because it uses what is known as  reflection to determine if one  

          type can be assigned to another type。 Essentially; it asks if it is OK via a cast to assign value to  

          CellState。 You could try to do this without the If statement; but then you risk an unnecessary  

          exception。 If it is permissible to assign; then the assignment is done via a two…step casting: 



          CellState(row; col) = DirectCast(DirectCast(value; Object); BaseType) 



                Here; you first convert the type to an Object; and then convert the type to BaseType; which  

          happens to be the type that the spreadsheet is declared as。 It is absolutely imperative that the  

          cast to the object is added; otherwise; the Visual Basic piler will plain that the cast is  

          not possible。 

                But suppose that the type cannot be directly assigned。 Let’s say that value references a  

          String that contains a number。 Then; using reflection; you can verify what ValueType and  

           BaseType are and perform the conversion yourself: 


…………………………………………………………Page 329……………………………………………………………

                                                        CH AP T E R   1 1   ■    L E A R N IN G   AB O U T   。 N E T  G E N E R I CS 307 



ElseIf TypeOf (value) Is String And _ 

       GetType(Double)。IsAssignableFrom(GetType(BaseType)) Then 



     The first part of the If statement asks if value is of type String。 The second part asks if Double  

can be assigned to BaseType。 If both are valid; it means the input is a String and the spread

sheet type is a Double; so to convert; you only need to call Double。Parse()。 

     Providing this automatic conversion functionality for the caller of the code does not save  

code; but it centralizes it and makes it general。 The caller will not generally need to worry about  

the most mon conversions; as they will happen automatically (you will have implemented  

them)。 For those conversions that cannot be done; a cast exception is thrown; just as the orig

inal object…based AssignCellState() would have thrown an exception。 

     The assignment is a series of casts and conversions that you need to do so that you can  

convert one type to another。 The main problem when converting types in this way is that the  

method…level  generics parameter is a type that is not related to the type…level  generics  

parameter。 



Dim obj As Object = DirectCast(value; Object) 

Dim dValue As Double = Double。Parse(CStr(obj)) 

Dim objDValue As Object = CType(dValue; Object) 

CellState(row; col) = DirectCast(objDValue; BaseType) 



     The first step is to convert the parameter into an object so that the cast operators that  

expect objects will work without the Visual Basic piler generating errors。 The If statement  

sai

返回目录 上一页 下一页 回到顶部 2 2

你可能喜欢的