Casting DataTypes with DirectCast, CType, TryCast

*爱你&永不变心* 提交于 2019-11-27 07:12:47

TryCast and DirectCast are casting operators that directly map to the CLR's support for casting. They can quickly cast an object of a base type to a derived type or unbox a value of a value type. DirectCast throws an exception when the cast isn't possible, TryCast returns Nothing if it failed. You typically want to favor DirectCast to catch programming mistakes.

CType allows a superset of conversions, ones that the CLR frowns on. The best example I can think of is converting a string to a number or date. For example:

Dim obj As Object
obj = "4/1/2010"
Dim dt As DateTime = CType(obj, DateTime)

Which you'll have to use if Option Strict On is in effect. If it is Off then you can do it directly:

Option Strict Off
...
    Dim dt As DateTime = obj

Very convenient of course and part of VB.NET's legacy as a dynamically typed language. But not without problems, that date is Unicorn day at stackoverflow.com but will be a day in January when a Briton enters the string. Unexpected conversions is the reason the CLR doesn't permit these directly. The explicit, never a surprise conversion looks like this:

Dim dt As DateTime = DateTime.Parse(obj.ToString(), _
    System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat)

Whether you should buy into Try/DirectCast vs CType vs explicit conversions is rather a personal choice. If you now program with Option Strict On then you should definitely start using Try/DirectCast. If you favor the VB.NET language because you like the convenience of dynamic typing then don't hesitate to stay on CType.

DirectCast is twice as fast for value types (integers...etc), but identical for reference types.

For more information see the "Conversion Functions, CType, DirectCast, and System.Convert" section on this MSDN page.

This page explains it well.

Reading it, I think that when you use DirectCast, you are sure that conversion will work without narrowing or expansion (in this case, numeric data). Whereas, CType will try to convert to it,with developer being aware of narrowing/expansion.

By "conversion" mean converting one datatype to another (e.g. string to integer, decimal to integer, object to string etc).

By "cast" mean changing one type of object into another type that is related to it by one of the following rules.

http://www.thedevheaven.com/2012/09/directcast-vs-ctype.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!