有没有一种整洁干净的方法来处理带产量的空值? [英] Is there a neat and clean way to handle nulls with Yields?
问题描述
While CommitReader.Read()
Yield New Commit() With {
.FirstValue = CommitReader.GetInt32(CommitReader.GetOrdinal("FirstValue")),
.SecondValue = CommitReader.GetString(CommitReader.GetOrdinal("SecondValue")).Trim(),
'Lots of values
End While
我知道我可以做这样的事情;但是有 24 个属性,我想让这部分尽可能干净
I know I can do something like this; however there are 24 properties and I would like to make this part as clean as possible
While CommitReader.Read()
new Commit (){
Dim index As Integer = reader.GetOrdinal("FirstValue")
If reader.IsDBNull(index) Then
FirstValue = String.Empty
Else
FirstValue = reader(index)
End If
index = reader.GetOrdinal("SecondValue")
If reader.IsDBNull(index) Then
SecondValue = String.Empty
Else
SecondValue = reader(index)
End If
}
End While
有没有更好的方法来处理这种类型的事情?我主要是一个 C# 开发人员,所以如果语法有点抱歉,我会在 VB 中使用它.
Is there a better way to handle this type of thing? I am mainly a C# developer so if the syntax is off a little sorry, I am winging it in VB.
推荐答案
很遗憾 SqlDataReader 没有像 DataRow 那样的通用 Field 扩展方法,但您可以定义自己的扩展方法(必须在模块中在 VB.NET 中)以帮助进行空检查,可能是这样的:
It's a shame that SqlDataReader doesn't have the generic Field extension method like DataRow does, but you could define your own extension method (has to be in a module in VB.NET) to help with the null checks, perhaps something like this:
<Extension>
Function GetValue(Of T)(rdr As SqlDataReader, i As Integer) As T
If rdr.IsDBNull(i) Then
Return Nothing
End If
Return DirectCast(rdr.GetValue(i), T)
End Function
然后像这样使用它:
While CommitReader.Read()
Yield New Commit() With {
.FirstValue = CommitReader.GetValue(Of Integer?)(CommitReader.GetOrdinal("FirstValue")),
.SecondValue = CommitReader.GetValue(Of String)(CommitReader.GetOrdinal("SecondValue")),
'Lots of values
End While
我尚未对此进行全面测试以确保它正确处理所有数据类型(可能值得查看 DataRowExtensions.Field 以了解它是如何做到的).
I haven't tested this fully to make sure it handles all data types appropriately (may be worth looking at DataRowExtensions.Field to see how it does it).
请注意,您使用 String.Empty 作为字符串的空"值,而这将使用 Nothing/null(我还必须删除 .Trim 调用以避免 NRE).如果您想要空字符串,则可以使用(重新添加 Trim):
Note that you are using String.Empty as the "null" value for strings, while this will use Nothing/null (I also had to remove the .Trim call to avoid NREs). If you want empty string instead, you could use (adding the Trim back in):
.SecondValue = If(CommitReader.GetValue(Of String)(CommitReader.GetOrdinal("SecondValue")), String.Empty).Trim()
您可能还想将 GetOrdinal 调用移出循环以提高性能.
You may also want to move the GetOrdinal calls out of the loop to improve performance.
这篇关于有没有一种整洁干净的方法来处理带产量的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!