在.net4中使用带有dbnull值的datareader

我听说框架4中有一个字段扩展方法允许一个接收来自datareader的空值,而不必经过第一次测试的过程,如果不是null那么……等等.这里有关于扩展方法的信息( MSDN) ),但我不知道如何在代码中使用它(相对较新的.net和以前从未使用过的扩展方法).如果有人能举一个例子,我将不胜感激.

这是我试图实现的,但是当在任一列中返回dbnull时它会返回错误.

Reader.Read()
Dim Val As Nullable(Of Double) = Reader.GetDecimal(0)
Dim Vol As Nullable(Of Long) = Reader.GetInt32(1)

解决方法

这些扩展方法涉及DataRow – 即DataTable ……而不是IDataReader(etc).
你可以用条件来做你想要的事情 – 虽然在VB中使用IIf,或者在C#中:

double? val = reader.IsDBNull(index) ? (double?) null : reader.GetDouble(index);
long? vol = reader.IsDBNull(index) ? (long?)null : reader.GetInt64(index);

您当然可以将它们作为实用程序方法包装起来,也许作为您自己的IDataReader上的自定义扩展方法:

public static class DataReaderExtensions
{
    public static int? ReadNullableInt32(this IDataReader reader,int index)
    {
        return reader.IsDBNull(index) ? (int?)null : reader.GetInt32(index);
    }
    public static long? ReadNullableInt64(this IDataReader reader,int index)
    {
        return reader.IsDBNull(index) ? (long?)null : reader.GetInt64(index);
    }
    public static double? ReadNullableDouble(this IDataReader reader,int index)
    {
        return reader.IsDBNull(index) ? (double?)null : reader.GetDouble(index);
    }
    public static string ReadNullableString(this IDataReader reader,int index)
    {
        return reader.IsDBNull(index) ? null : reader.GetString(index);
    }
    // etc
}

(抱歉使用c#作为示例 – 但你可以阅读c#比写出准确的vb.net更好)

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...