如何将可空类型转换为其基础类型?

时间:2013-09-10 13:35:00

标签: .net type-conversion nullable

由于某些特殊原因,我不得不将数据存储到DataTable中,并意识到它不支持可空类型:抛出System.NotSupportedException:DataSet不支持System.Nullable<>。有没有比枚举类型和为每个可空类型编写自定义代码更有效的转换方法?

1 个答案:

答案 0 :(得分:1)

但它支持可空类型,AllowDbNull默认为true

var table = new DataTable();
table.Columns.Add("NullableInt", typeof(int));
table.Rows.Add(1);
table.Rows.Add(2);
table.Rows.Add(3);
table.Rows.Add((int?)null);

使用支持可空类型的DataRow extension methods,例如:

foreach(DataRow row in table.Rows)
{
    int? value = row.Field<Int32?>("NullableInt");
    // modify the value with SetField:
    row.SetField<Int32?>("NullableInt", null); 
    // or: 
    row.SetField("NullableInt", (int?)null);
}