我在此代码中遇到“无效转换”异常,该异常位于网格的 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 文件填充的,该文件的架构将值定义为值为 0 的整数。正如人们所看到的,这就是细胞的值(value)。那么为什么不能将其拆箱为整数以便我可以对其进行评估呢?
最佳答案
该值是除int
之外的某种类型,例如 double
或字符串
。即使它是隐式可转换类型,例如short
,除非其类型为int
,否则无法直接拆箱为int
。您可以使用Convert.ToInt32(value)
转换值。
关于c# - 为什么 0 不能拆箱为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18924702/