[.net]DirectCast Vs. CType 哪種好?
DirectCast 不會將 Visual Basic 執行階段 Helper 常式用於轉換,因此在資料型別 Object 間進行轉換時,它可提供的效能比 CType 還好。
使用 DirectCast 關鍵字的方式與使用 CType 函式 和 TryCast 關鍵字的方式相同。提供運算式做為第一個引數,並提供型別以將它轉換成第二個引數。DirectCast 需要這兩個引數之資料型別之間的繼承或實作關聯性。這表示其中一個型別必須繼承自另一個型別或實作另一個型別。
Introduction
Background
The first thing to understand is that CType and DirectCast are not the same thing. Only CType can convert the underlying object to a new instance of an object of a different type. For example, if you want to turn an integer into a string. Since an Integer doesn't inherit a String, a new instance of a String object must be created in order to store the number as a String. CType can do this, DirectCast cannot. Note: There are other ways to do this too such as the Convert.ToString method or CStr().
Dim MyInt As Integer = 123
Dim MyString1 As String = CType(MyInt, String)
Dim MyString2 As String = DirectCast(MyInt, String) ' This will not work
What DirectCast and CType do have in common is their ability to convert an object to a new type based on inheritance or implementation. For example, if you have a String but it is stored in a variable of type Object, you can use DirectCast or CType to treat that variable as an object of type String because type String inherits type Object. In this case, the underlying data in memory is not actually changing, nor is any processing happening on that data.
Dim MyObject As Object = "Hello World"
Dim MyString1 As String = CType(MyObject, String)
Dim MyString2 As String = DirectCast(MyObject, String) ' This will work
The danger: You MUST know what type you are dealing with before using DirectCast. If you have a variable of type Object and you use DirectCast to treat it as a String, you'd better be sure that variable actually contains a String (or Nothing). If an Integer somehow found its way into that variable an exception will be thrown.
A way to check in code if DirectCast will work is by using the TypeOf operator:
If TypeOf MyObject Is String Then
So, assuming you are doing a conversion based on inheritance or implementation, you have a choice: DirectCast vs. CType. Which is better?
The Answer
DirectCast on a reference type:
8.7885
CType on a reference type
11.718
DirectCast on a value type
18.5535
CType on a value type
39.06
0 comments: