gpt4 book ai didi

c# - 当一个项目可能为 null 时,如何正确地将其转换为 DataSet 中的项目?

转载 作者:太空狗 更新时间:2023-10-30 00:36:50 25 4
gpt4 key购买 nike

我有一个存储过程返回的数据集,其中的一项可能为空。我正在尝试将数据集中的每一行转换为强类型对象,但我似乎无法正确转换空值。

我已经创建了一个场景模型,如下所示:

DataSet ds = new DataSet();
ds.Tables.Add(new DataTable());
ds.Tables[0].Columns.Add("Name", typeof(string));
ds.Tables[0].Columns.Add("Amount", typeof(decimal));
ds.Tables[0].Rows.Add("My Name Here", null); //create row with a null item

DataRow dataRow = ds.Tables[0].Rows[0];

Person p = new Person
{
Name = (string)dataRow["Name"],
Amount = (decimal)dataRow["Amount"]
}

不幸的是,我遇到了以下异常:System.InvalidCastException: Specified cast is not valid.

如果我尝试使用可空类型(十进制?),我会收到此错误:System.NotSupportedException: DataSet does not support System.Nullable<>.

在调试器中,我对 dataRow["Amount"] 中的值进行了以下测试:

dataRow["Amount"] is decimal (false)
dataRow["Amount"] is decimal? (false)
dataRow["Amount"] == null (false)
dataRow["Amount"] is object (true)

我所能确定的是它是某种对象...这不是特别有用。

你们有谁能看出我哪里做错了吗?

最佳答案

您可以使用 dataRow.IsNull("Amount")Convert.IsDBNull(dataRow["Amount"])(dataRow["Amount"] 作为十进制)!= null

关于c# - 当一个项目可能为 null 时,如何正确地将其转换为 DataSet 中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/652456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com