本文介绍了VB CStr、CDate、CBool​​ 等与 DirectCast 相比,无需转换即可进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常避免使用 VB 的内置转换函数(CStr、CDate、CBool​​、CInt 等),除非我需要进行实际转换.如果我只是将对象转换为字符串,那么我通常使用 DirectCast 或 TryCast,假设 CStr 等正在做一些我不需要的额外内容.但有时 DirectCast 语法有点麻烦,如下例所示.

I usually avoid VB's built-in conversion functions (CStr, CDate, CBool, CInt, etc.) unless I need to do an actual conversion. If I'm just casting, say from an object to a string, I normally use either DirectCast or TryCast, under the assumption that CStr, etc., are doing some extra stuff I don't need. But sometimes the DirectCast syntax is a little cumbersome, as in the following example.

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

SqlDataReader.Item 返回一个对象,需要将其转换为字符串.CStr 更易于阅读、输入和解释 (IMO).

SqlDataReader.Item returns an Object, which needs to be cast to a String. CStr is easier to read, type, and explain (IMO).

我的问题是,我使用哪一个重要吗?我是否应该只使用 CStr(以及 CDate 和 CBool​​ 等)而不用担心我假设这些函数正在做的额外工作?

My question is, does it matter which one I use? Should I just go with CStr (and CDate and CBool, etc.) and not worry about the extra work I assume those functions are doing?

使用这些功能还有其他缺点吗?

Is there any other downside to using these functions?

推荐答案

这个是一篇很好的帖子,在评论中讨论了 DirectCast 与 CType 类型转换和变体.

This is a good post with discussion in the comments about DirectCast versus the CType casts and variations.

简而言之,如果您想明确说明它并知道会发生什么,建议使用 DirectCast.另一方面,Paul Vick(VB 技术负责人)的评论说这并不重要,只需使用 CType 变体即可.

In short, if you want to be explicit about it and know what to expect, DirectCast is suggested. On the other hand, a comment by Paul Vick (VB Technical Lead) says it doesn't matter much and to just use the CType variations.

从该帖子中收集到的一些有用链接:

Some useful links gleaned from that post:

  • How should I cast in VB.NET?
  • DirectCast Revealed (post on Paul Vick's blog)

这篇关于VB CStr、CDate、CBool​​ 等与 DirectCast 相比,无需转换即可进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 14:51