VB CStr, CDate, CBool, etc. vs. DirectCast for casting without conversion

前端 未结 3 1374
走了就别回头了
走了就别回头了 2021-01-06 04:56

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

相关标签:
3条回答
  • 2021-01-06 05:39

    In your example, you could just use:

    value1 = reader("COLUMN1").ToString()
    

    It will return the contents of the column as a string.

    I always tend to favour using ToString() on an object if I can. Sometimes an object's ToString() method will return things like the class name of the object, rather then a content, so .ToString() isn't always an option.

    I don't see the need for any of the VB functions CStr, CInt, etc, since the .NET framework provides plenty of good alternatives. For example.

    Dim value As Integer = Convert.ToInt32(reader("Number").ToString())
    

    Is a good way of converting a string to an int. It's worth reading up on these conversion methods, since the old VB style functions are only there for backwards compatability.

    0 讨论(0)
  • 2021-01-06 05:46

    Most of the time, I use CStr, CInt, CBool and CType because it's shorter and easier to read. There might be a slight performance cost but most of the time it doesn't matter. It's good to know the differences between CType, TryCast, DirectCast, and others though.

    0 讨论(0)
  • 2021-01-06 05:55

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

    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)
    0 讨论(0)
提交回复
热议问题