我想这样做:

myYear = record.GetValueOrNull<int?>("myYear"),

注意将可空类型作为泛型参数。

因为GetValueOrNull函数可以返回null,我的第一次尝试是:

public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
  where T : class
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
    {
        return (T)columnValue;
    }
    return null;
}

但我现在得到的错误是:

类型'int?'必须是引用类型,以便在泛型类型或方法中使用它作为参数'T'

没错!Nullable<int>是一个结构体!所以我尝试将类约束改为结构约束(作为副作用不能再返回null):

public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
  where T : struct

现在是作业:

myYear = record.GetValueOrNull<int?>("myYear");

给出以下错误:

类型'int?'必须是一个非空值类型,以便在泛型类型或方法中使用它作为参数'T'

是否可以将可空类型指定为泛型参数?


当前回答

只需要做一些不可思议的类似的事情。我的代码:

public T IsNull<T>(this object value, T nullAlterative)
{
    if(value != DBNull.Value)
    {
        Type type = typeof(T);
        if (type.IsGenericType && 
            type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
        {
            type = Nullable.GetUnderlyingType(type);
        }

        return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :
            Convert.ChangeType(value, type));
    }
    else 
        return nullAlternative;
}

其他回答

较短的方法:

public static T ValueOrDefault<T>(this DataRow reader, string columnName) => 
        reader.IsNull(columnName) ? default : (T) reader[columnName];

int返回0,int返回null ?

下面是一个我用了很多年的扩展方法:

public static T GetValue<T>(this DbDataReader reader, string columnName)
{
    if (reader == null) throw new ArgumentNullException(nameof(reader));
    if (string.IsNullOrWhiteSpace(columnName))
        throw new ArgumentException("Value cannot be null or whitespace.", nameof(columnName));

    // do not swallow exceptions here - let them bubble up to the calling API to be handled and/or logged
    var index = reader.GetOrdinal(columnName);
    if (!reader.IsDBNull(index))
    {
        return (T)reader.GetValue(index);
    }
    return default;
}

将返回类型更改为Nullable<T>,并调用具有非Nullable参数的方法

static void Main(string[] args)
{
    int? i = GetValueOrNull<int>(null, string.Empty);
}


public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
        return (T)columnValue;

    return null;
}

以防它帮助别人-我以前用过这个,似乎做什么我需要它…

public static bool HasValueAndIsNotDefault<T>(this T? v)
    where T : struct
{
    return v.HasValue && !v.Value.Equals(default(T));
}

只需对原始代码做两件事——删除where约束,并将最后一个返回从return null更改为return default(T)。这样你就可以返回你想要的任何类型。

顺便说一下,可以通过将if语句更改为if (columnValue != DBNull.Value)来避免使用is。