为什么0 unbox不会整数?

时间:2013-09-20 19:47:19

标签: c# exception casting integer

我在这段代码中遇到了一个“无效的强制转换”异常,它位于网格的mousedown中:

// Get the index of the row and column the mouse is over.
    rowIndexFromMouseDown = grdSale.HitTest(e.X, e.Y).RowIndex;
    colIndexFromMouseDown = grdSale.HitTest(e.X, e.Y).ColumnIndex;
// Drag only if we're not over header, are over count, and there are some tickets
    if ((rowIndexFromMouseDown != -1)
        && (colIndexFromMouseDown == 2)
        && ((int)grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"].Value > 0))

从即时窗口:

?rowIndexFromMouseDown
2
?colIndexFromMouseDown
2
?grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"].Value
0
?(int)grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"].Value
Cannot unbox '(grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"]).Value' as a 'int'

网格单元格不显示任何内容,但网格是从XML文件填充的,该文件的架构将值定义为整数,值为零。正如人们所看到的那样,这就是细胞的价值。那么为什么不能将它拆箱成一个整数以便我可以对它进行评估呢?

1 个答案:

答案 0 :(得分:3)

除了int之外,该值是某种类型,例如doublestring。即使它是隐式可转换类型,例如short,除非其类型为int,否则无法直接取消装箱到int。您可以使用Convert.ToInt32(value)转换价值。

相关问题