DirectCast和CType的区别

Introduction

我们何时该使用 CType, 何时又该使用 DirectCast, 哪一个更好? 一个简单的答案是: 对于值类型, DirectCast 的速度是 CType 的两倍, 引用类型则基本相同.

Background

CType 和 DirectCast 不是同一个东西. 只有 CType 能将一个对象转换成一个新类型的实例. 假设你要把 Integer 类型转换成 String 类型, 由于 Integer 和 String 之间没有继承关系, 必须建立一个新的 String 实例来存储这个数字对应的字符串. CType 可以做到, 而 DirectCast 不行. (Note: 也可以用 Convert.ToString 或 CStr 来实现)

Dim MyInt As Integer = 123
Dim MyString As String = CType(MyInt, String)
Dim MyString2 As String = DirectCast(MyInt, String) ' This will not work

DirectCast 和 CType 的共同之处在于它们都能将对象转换成一个和原对象有继承 (Inherit) 或实现 (Implement) 关系的类型. 比如, 如果你有一个字符串存在 Object 变量里, 你可以用 DirectCast 或 CType 来将它转换成 String 类型, 因为 String 继承于 Object. 此例中, 内存中的数据并没有被改变或处理.

Dim MyObject As Object = "Hello World"
Dim MyString1 As String = CType(MyObject, String)
Dim MyString2 As String = DirectCast(MyObject, String)

The danger: 使用 DirectCast 之前你必须知道要处理的是什么类型. 如果你要把一个 Object 变量用 DirectCast 转换成 String, 你必须确定这个变量确实包含一个 String (或者为 Nothing). 如果它包含一个 Integer 之类的东西, 会抛出一个异常.

我们可以用 TypeOf 运算符来检查能否使用 DirectCast:

If TypeOf MyObject Is String Then

现在, 当你要进行基于继承和实现的转换时, 你有两个选择: DirectCast 和 CType. 哪一个更好呢?

The Answer

答案是 DirectCast. .NET 文档中说: DirectCast 不使用 Visual Basic 运行时辅助例程来进行转换, 所以可以提供比 CType 更好的效率.

文中 包含的工程对各种情况进行了测试: DirectCast vs. CType, 值类型和引用类型. 引用类型指 Form、Control、String 和 Class 等, 值类型指 Integer, Double 和 Structure 等. 下面的测试结果是将每项转换进行 100 万次所需的毫秒数:

DirectCast, 引用类型:

8.7885

CType, 引用类型:

11.718

DirectCast, 值类型:

18.5535

CType, 值类型:

39.06

结论: DirectCast 对值类型的效率几乎是 CType 的两倍, 对引用类型也比 CType 效率好一点.

Note: 随后的测试的结果相近, 读者可以自己试一下.

另外一个使用 DirectCast 的原因是, 它不是基于 VB.NET 的特定实现, 因此可以更容易地移植到其它语言. 因此 C#... 等程序员可能会更容易读懂你的程序.

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/cxlooing/archive/2009/11/09/4789947.aspx

原文地址:https://www.cnblogs.com/gyxdbk/p/1631351.html