代码之家  ›  专栏  ›  技术社区  ›  rybosome

如何在VB.NET中复制对象类型?

  •  0
  • rybosome  · 技术社区  · 16 年前

    Private Sub AddTableRow(ByRef originalTable As System.Web.UI.WebControls.Table)
    
            Dim originalRow As System.Web.UI.WebControls.TableRow = originalTable.Rows(1)
            Dim insertingRow As New System.Web.UI.WebControls.TableRow
            Dim insertingCells(originalRow.Cells.Count) As System.Web.UI.WebControls.TableCell
            Dim index As Integer = 0
    
            For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells
    
                insertingCells(index) = New System.Web.UI.WebControls.TableCell
                insertingCells(index).Controls.Add(cell.Controls.Item(0))
    
                index += 1
            Next
    
            insertingRow.Cells.AddRange(insertingCells)
    
            originalTable.Rows.Add(insertingRow)
    
        End Sub
    

    但我在倒数第二行得到一个空引用异常,

    insertingRow.Cells.AddRange(插入单元格)

    …我不知道为什么。是因为每个单元格的内容没有用新对象初始化吗?如果是的话,我该怎么办?

    编辑:

    For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells
            Dim addedContent As New Object
            Dim underlyingType As Type = cell.Controls.Item(0).GetType
    
            addedContent = Convert.ChangeType(cell.Controls.Item(0), underlyingType)
            insertingCells(index) = New System.Web.UI.WebControls.TableCell
            insertingCells(index).Controls.Add(addedContent)
    
            index += 1
    Next
    

    通过使用调试器,我看到这个策略正在工作——但是额外的表行仍然没有出现……当我静态地执行此操作时,仍然会出现。

    1 回复  |  直到 16 年前
        1
  •  1
  •   Dan Tao    16 年前

    我想你的罪魁祸首可能是这句话:

    Dim insertingCells(originalRow.Cells.Count) As TableCell
    

    令人困惑的是,在VB.NET的数组声明中指定的数字是上限,而不是元素数。所以呢 Dim ints(10) As Integer Integer() 数组 元素,而不是10(10将是数组的最高索引)。

    请尝试以下操作:

    Dim insertingCells(originalRow.Cells.Count - 1) As TableCell