[译]Visual Basic 2005在语言上的增强(六)IsNot运算符和TryCast语句

友情提醒,本文翻译的一处有误,请网友们务必结合评论来看本期翻译!

IsNot运算符


IsNotIs的反义运算符。在引用一个对象前,要先检查它是否已被初始化,而在过去我们都使用这种很别扭很老套的方式:
If Not myObj Is Nothing Then

IsNot使你可以进行直接的比较,免除了使用 Not运算符的烦恼:
If myObj IsNot Nothing Then

同样地,你在比较两个对象实例是否不同时,也不必再使用 Not运算符了:
If MyObj1 IsNot MyObj2 Then

别看这只是个简单的变化, IsNot弥补了Visual Basic语言一致性不足的一个缺点,你的代码将变得更加简洁了。

TryCast语句

在Visual Basic 2003里,你可以使用以下两种之一的方法把一个对象的类型转换为另一个类型:
Dim p As Product
p = CType(obj, Product)
p = DirectCast(obj, Product)

上面,你使用 CType把一个类型转换成了另一个,而 DirectCast要求这两个对象间有继承或是实现接口的关系(作者这里的讲解 有误CTypeDirectCast的实际区别是 DirectCast要求对象的运行时类型与指定的转换类型要相同,而 CType的运行效率的运行效率略低些,涕淌注)。但这里的问题是,无论你使用哪种方法,如果obj无法被转换或铸造(转换是“convert”,铸造是“cast”,作者在有的地方混淆了convert和cast的区别,其实它们的区别就是 CTypeDirectCast的区别。但是笔者认为没有必要去抠这个字眼,因此我在其他地方统一译作“转换”,涕淌注)成Product类型的话,那么将导致程序的运行时异常。

用新的 TryCast语句吧。它和 CType或者是 DirectCast的作用方式一样,只不过如果类型转换无法完成时,将返回一个 Nothing值给对象:
p = TryCast(obj, Product)
If p IsNot Nothing Then
    '使用p对象……
End If


@以下是原文供大家参考@

IsNot Operator

The IsNot operator provides a counterpart to the Is operator. Instead of the clunky and often-used check that an object has been instantiated before you reference it:
If Not myObj Is Nothing Then

IsNot lets you use a direct comparison, eliminating the Not operator:
If myObj IsNot Nothing Then

Similarly, you can eliminate the Not operator when checking if two object instances are different:
If MyObj1 IsNot MyObj2 Then

Although it's a simple change, IsNot fills a consistency gap in the Visual Basic language that helps make your code clearer.

TryCast Statement

In Visual Basic 2003, you can cast one type of object to another type in one of two ways:
Dim p As Product
p = CType(obj, Product)
p = DirectCast(obj, Product)

Here, you use CType to convert from one type to another, while DirectCast requires there be an inheritance or implementation relationship between the objects. The problem with these is that you'll get a run-time exception in either case if obj cannot be converted or cast to type Product.

Enter the new TryCast statement. You use it the same way as CType or DirectCast, except that the result returned is Nothing if the cast cannot be accomplished:
p = TryCast(obj, Product)
If p IsNot Nothing Then
    'use the p object...
End If
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值