NET 中 DirectCast()与 CType()的区别

我是一个经验丰富的 C/C + +/C # 程序员,刚刚进入 VB.NET。我通常使用 CType (以及 CInt、 CBool、 CStr)进行类型转换,因为它的字符数较少,而且是我接触到的第一种类型转换方法,但我也知道 DirectCast 和 TryCast。

简单地说,DirectCast 和 CType 之间有什么区别(强制转换的效果、性能等等)吗。

90845 次浏览

The first thing to note is VB.NET does not have a direct analog to C#'s (type)instance casting mechanism. I bring this up because it's useful as a starting point and common reference in comparing the two VB.NET operators (and they are operators, not functions, even though they have function semantics).

DirectCast() is more strict than the C# casting operator. It only allows you to cast when the item being cast already is the type you are casting to. I believe it will still unbox value types, but otherwise it won't do any conversion. So, for example, you can't cast from short to int, like you could with a C# (int) cast. But you can cast from an IEnumerable to an array, if your underlying IEnumerable object variable really is an Array. And of course you can cast from Object to anything, assuming the type of your object instance really is somewhere below your cast type in the inheritance tree.

This is desirable because it's much faster. There's less conversion and type checking that needs to take place.

CType() is less strict than the C# casting operator. It will do things you just can't do with a simple (int)-style cast, like convert a string to an integer. It has as much power as calling Convert.To___() in C#, where the ___ is the target type of your cast.

This is desirable because it's very powerful. However, this power comes at the cost of performance; it's not as fast as DirectCast() or C#'s cast operator because it might need to do quite a lot of work to finish the cast. Generally you should prefer DirectCast() when you can.

Finally, you missed one casting operator: TryCast(), which is a direct analog to C#'s as operator.

With CType you can write something like Ctype("string",Integer). But with DirectCast the above statement would give a compile time error.

 Dim a As Integer = DirectCast("1", Integer) 'Gives compiler error
Dim b As Integer = CType("1", Integer) 'Will compile

DirectCast is more restrictive than CType.

For example, this will throw an error:

Sub Main()
Dim newint As Integer = DirectCast(3345.34, Integer)
Console.WriteLine(newint)
Console.ReadLine()
End Sub

It will also be shown in the Visual Studio IDE.

This however, does not throw an error:

Sub Main()
Dim newint As Integer = CType(3345.34, Integer)
Console.WriteLine(newint)
Console.ReadLine()
End Sub