Joh*_*ant 4 vb.net type-conversion
除非我需要进行实际转换,否则我通常会避免使用VB的内置转换函数(CStr,CDate,CBool,CInt等).如果我只是在演员,从一个对象说到一个字符串,我通常使用DirectCast或TryCast,假设CStr等正在做一些我不需要的额外的东西.但有时DirectCast语法有点麻烦,如下例所示.
Dim value1 As String
Dim value2 As String
Using cn As New SqlConnection(cnStr)
Using cmd as New SqlCommmand(sqlStr, cn)
Using reader = cmd.ExecuteReader()
While reader.Read()
value1 = DirectCast(reader("COLUMN1"), String)
value2 = CStr(reader("COLUMN1"))
End While
End Using
End Using
End Using
Run Code Online (Sandbox Code Playgroud)
SqlDataReader.Item返回一个Object,需要将其强制转换为String.CStr更易于阅读,输入和解释(IMO).
我的问题是,我使用哪一个是否重要?我应该选择CStr(以及CDate和CBool等)而不担心我认为这些功能正在做的额外工作吗?
使用这些功能还有其他缺点吗?
Ahm*_*eed 10
这是一篇很好的文章,在有关DirectCast与CType演员表和变体的评论中进行了讨论.
简而言之,如果您想明确它并知道会发生什么,建议使用DirectCast.另一方面,Paul Vick(VB技术主管)发表的评论称,使用CType变体并不重要.
从该帖子中收集了一些有用的链接: