VB.Net语言方面的改进
点击次数:48 次 发布日期:2008-11-06 08:06:51 作者:源代码网
|
在新的Visual Basic中,这些都将成为过去。Visual Basic.NET将真正支持oop。继承(inheritance)、多态(polymorphism)以及重载(overloading)。当然还不止这些。包括一些新的数据结构、结构性的错误控制(Error Handing)以及线程。这些都将被新的VB所支持。 继承 假设你编写了一个只包含一个函数的名称为BaseClass的基本 类: Function GetCustomerName() " Do some stuff End Function 如果你想建立一个新类,并使用BaseClass中的GetCustomerName 函数。但有不想重写一编代码。那么通过继承,你可以这样编写新类: Inherits BaseClass Function GetCustomerID() " Do some stuff End Function 重载 重载就是建立两个具有同样你名称但是参数属性不同的函数的过 程。假设有GetCustomID函数根据输入输出用户的ID号码。那么该函数可能有以下两种类型: Function GetCustomerID(custname as string) As Integer " 通过用户名获得用户ID End Function Function GetCustomerID(purch as long) As Integer " 根据购物单号码获得用户ID End Function 通过重载,你就可以根据不同类型的输入调用同一个函数。 实际上现在的VB在某种程度上提供了重载的功能,考虑下面的函数: Function GetCustomID(vIN As Variant) As Long GetCustomID = vIN End Function 你可以以下面两种方式调用 ID = GetCustomID("123") 或者 ID = GetCustomID(123) 那么为什么还要在新版本中引进重载呢?这是因为新的Visual Basic引进了新的特性:类型安全(default type safety)。在Visual Basic.NET中,Variant类型将不复存在,详细的介绍看下面关于升级部分的内容。 多态 多态是在一个类中重新定义一个函数的过程。例如你需要建立一 个基于BaseClass类的子类,但是又需要重新编写GetCustomerName函数,在新版的VB中,你就可以这样写: Inherits BaseClass Function GetOrders() Overrides Function GetOrders() ... End Function 线程 新的Visual Basic语言结构部分将包含建立多线程,一个线程建 立的范例如下: set t = New Thread(New Threadstart (AddressOf(BaseClass.Function1)) 从上面的范例还可以看到,Visual Basic.NET中的AddressOf函 数将真正返回函数的指针。这在进行API调用,例如回调函数方面将是很有帮助的。 错误处理(Error Handling) Visual Basic.NET的另外一个大的改进就是错误处理。Visual Basic将提供try…catch…finally结构,就象Delphi中的那样(微软的原文是:just like those "respectable" languages :-))。例如: Sub SafeWrite() Try Open "Testfile" ... Write #1 Catch Kill "Testfile" Finally Close #1 End Try End Sub 升级 当代码升级后,Visual Basic.NET会建立一个新的升级工程。下 面通过几个例子来说明你的代码做了那些升级 源代码网推荐 源代码网供稿. |
