VB2005语言新功能[1]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

有以下主要新功能

运算符重载/部分类/Continue 关键字/Using 关键字/拆分存取访问/泛型支持

运算符重载
 Dim ShortSpan, LongSpan, TotalSpan As TimeSpan
 ShortSpan = TimeSpan.FromMinutes(100)
 LongSpan = TimeSpan.FromDays(14)
 TotalSpan = ShortSpan + LongSpan
 Console.WriteLine(TotalSpan.TotalMinutes)
 为什么可以直接TotalSpan = ShortSpan + LongSpan这样呢,原因是TimeSpan类对+号运算符进行了重载,如
  Public Shared Operator+(objA As MyClass,
    objB as MyClass) As MyClass
      ' (Code goes here.)
  End Operator

部分类
 所谓部分类,就是把类定义为类的一部分,一个类可以有多个部分类组成而形成一个完整的类
 部分类的主要作用用于把类的定义分别存于不同的文件中,使用如下
 比如在文件TestClass_1.vb中存放下面代码
 Partial Public Class 存放
    Public Sub TestMethodA()
        Console.WriteLine("Method A called.")
    End Sub
 End Class
 在文件TestClass_2.vb中存放下面代码
 Partial Public Class TestClass
     Public Sub TestMethodB()
         Console.WriteLine("Method B called.")
     End Sub
 End Class

  而调用时和存放在一起没有什么区别
  Dim Obj As New TestClass()
 Obj.TestMethodA()
 Obj.TestMethodB()

 
Continue 关键字
 有3中使用方法
 Continue For、Continue Do 和 Continue While
 分别应用于
 For ... Next, Do ... Loop, or While ... End While中
 如下例子
 For i = 1 to 1000
    If i Mod 5 = 0 Then
        ' (Task A code.)
        Continue For
    End If
    ' (Task B code.)
 Next

Using 关键字
 Using表达式用于控制资源释放
 如下:
 Using NewFile As New _
   System.IO.StreamWriter("c:\MyFile.txt")
     NewFile.WriteLine("This is line 1")
     NewFile.WriteLine("This is line 2")
 End Using
 
 ' The file is closed automatically.
 ' The NewFile object is no longer available here.
 这样,当使用了using关键字时,VB2005会自动调用对象的Dispose()方法释放资源

拆分存取访问
 在以前有以下三种访问方式
 公用 (Public)
 友元 (Friend)
 私用 (Private)
 但是,当碰到下面情况时会碰到一下问题,如只想给访问Status的权限,而不让非友元类设置Status的值
  Public Property Status() As Integer
     Get
         Return _Status
     End Get
     Set(ByVal value As Integer)
         _Status = value
     End Set
  End Property
 这时就比较难以处理了,然而在VB.2005中可以使用如下代码实现
 Public Property Status() As Integer
     Get
         Return _Status
     End Get
     Friend Set(ByVal value As Integer)
         _Status = value
     End Set
 End Property

本文关键:VB2005语言新功能
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top