你好,
IDE Visual Studio 2010
.NET 3.5
平台 WinForms
这个SO问题“从DataRow获取值的区别”被提到了。
我有一个带有列[ID] INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
的数据库表。 当查询该表并将值存储在本地变量中时,我会得到一个无效的转换异常; 示例代码:
string sQuery = @"
SELECT [ID], [Description]
FROM [Sources]
ORDER BY [Description] ";
using (DataTable dtSources = SQLHelper.Fetch(sQuery))
{
foreach (DataRow drSource in dtSources.Rows)
{
int iID = drSource.Field<int>("ID"); // InvalidCastException
string sDescrption = drSource.Field<string>("Description");
}
}
当执行步骤并在错误行上执行“快速查看”时,我发现通过将该行更改为drSource.Field<object>("ID")
,单元格值类型为short
而不是int
。为什么会发生这种情况,因为在表定义中,它明确地是int
?此外,short
应隐式转换为int
,因为short
更小,应该“适合”吧?
int iID = (int)drSource["ID"];
或者int iID = Convert.ToInt32(drSource["ID"]);
可以解决问题(因为int iID = drSource.Field<int>("ID");
甚至不允许将short隐式转换为int),但是事先检查“是否可转换”也可能是个好主意。 - that0th3rGuy