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

类别:.NET开发 点击:0 评论:0 推荐:
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

本文地址:http://com.8s8s.com/it/it42209.htm