Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net扩展方法SQL Datareader GetValuerDefault_.net_Vb.net_Extension Methods_Datareader - Fatal编程技术网

.net扩展方法SQL Datareader GetValuerDefault

.net扩展方法SQL Datareader GetValuerDefault,.net,vb.net,extension-methods,datareader,.net,Vb.net,Extension Methods,Datareader,关于使用ExtensionMethod的良好实践的问题 我希望获取datareader的值,但有时我希望避免空值,因为VB.net和C#是不同的(默认函数在VB中不存在),我这样做: Imports System.Runtime.CompilerServices Imports System.Data.SqlClient Public Module ExtensionMethodeSQL <Extension()> Public Function GetValueOrDefaul

关于使用ExtensionMethod的良好实践的问题

我希望获取datareader的值,但有时我希望避免空值,因为VB.net和C#是不同的(默认函数在VB中不存在),我这样做:

Imports System.Runtime.CompilerServices
Imports System.Data.SqlClient

Public Module ExtensionMethodeSQL

<Extension()>
Public Function GetValueOrDefault(Of T)(ByVal dtReader As SqlDataReader, ByVal index As Integer) As T

    If dtReader.IsDBNull(index) = True Then
        If GetType(T).IsValueType = True Then
            Dim defaultValue As T = Nothing
            Return defaultValue
        Else
            Return Nothing
        End If
    Else
        Return CType(dtReader.GetValue(index), T)
    End If

End Function

<Extension()>
Public Function GetValueOrDefault(Of T)(ByVal aString As SqlDataReader, ByVal fieldName As String) As T
    Return aString.GetValueOrDefault(Of T)(aString.GetOrdinal(fieldName))
End Function
End Module
导入System.Runtime.CompilerServices
导入System.Data.SqlClient
公共模块扩展方法SQL
公共函数GetValuerDefault(Of T)(ByVal dtReader作为SqlDataReader,ByVal索引作为整数)作为T
如果dtReader.IsDBNull(index)=True,则
如果GetType(T).IsValueType=True,则
将默认值设置为T=无
返回默认值
其他的
一无所获
如果结束
其他的
返回CType(dtReader.GetValue(index),T)
如果结束
端函数
公共函数getValuerDefault(Of T)(ByVal aString作为SqlDataReader,ByVal fieldName作为字符串)作为T
返回aString.GetValueOrDefault(共T个)(aString.GetOrdinal(字段名))
端函数
端模块
那好吗?有什么可以让它变得更好的吗

不确定是否使用CType,trycast是否更适合ValueType


Thx

默认函数在vb中不存在)
默认索引器在vb中称为
项。另一种方法是:最好使用简单函数,还是应该使用methode扩展?如果您愿意,您可以对它们进行扩展。您可能希望使用
DbDataReader
而不是
SqlDataReader,除非您只使用一个SQLSvr。就我个人而言,我认为重载不会使它更可读/可控(vb中不存在默认函数)
默认索引器在vb中称为
Item
。另一种方法是:最好使用简单函数,还是应该使用methode扩展?如果您愿意,您可以对它们进行扩展。您可能希望使用
DbDataReader
而不是
SqlDataReader,除非您只使用一个SQLSvr。就个人而言,我不认为重载使它更可读/可控