如果你没有使用Visual Studio.NET,那么可以使用vbc.exe 编译vb.NET源程序,vbc.exe 是在安装.NET Framework时自动安装的。举个例子,当你把源代码保存到文件Employee.vb中后,在Employee.vb相同的目录下输入vbc Employee.vb。
现在我们回到list4的代码中,在Main sub中声明了Employee类的对象变量,这个变量叫anEmployee.
| Dim anEmployee As Employee |
anEmployee初始化Employeer时必须使用关键字new.
| anEmployee = New Employee() |
现在我们有一个Employeer的对象,你可以使用它的功能了。在我们的例子中,调用了PrintSalary 方法。
| anEmployee.PrintSalary() |
你也可以把Main Sub放在类中,采用这种方法就不需要模块,如list5中所示
| Listing 5: Moving the Main sub to the class itself Class Employee Dim salary As Decimal = 40000 Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ’ print the salary to the Console System.Console.Write(salary) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee.PrintSalary() End Sub End Class |
注意在PrintSalary 方法中调用了System.Console.Write意味着调用了Console类的write方法并且Console类是System名字空间的一部分,关于名字空间我们将在后面讲述。
名字空间
当写.NET应用程序时,需要写类和其他数据类型。为使应用程序更有条理,组织性更好,需要将他们聚合进名字空间中,这也是微软用.NET Framework类库的原因。微软.NET Framework sdk文档中的.NET Framework类库中包含了80多个名字空间,包括常用的重要的名字空间,如System, System.IO, System.Drawing, System.Windows.Forms等等。举例而言,在Employee类中的PrintSalary 方法,我们使用了system名字空间中的console类。
如果在程序中要经常使用一个名字空间,可以采取引用该名字空间的方法,这样在每次调用其成员时就用不作重复写名字空间了。例如你可以象下面这样改写list4和list5。
| Listing 6: Importing a namespace Imports System Class Employee Dim salary As Decimal = 40000 Dim yearlyBonus As Decimal = 4000 Public Sub PrintSalary() ’ print the salary to the Console Console.Write(salary) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee.PrintSalary() End Sub End Class |
现在你可以在PrintSalary方法中使用名字空间而不用提及名字空间,因为名字空间已经引用了。
在不同的名字空间允许有相同名字的类,正确地引用一个类最普通的实践是提到过的在类名前面的名字空间。如system名字空间中的Console的引用方法是:System.Console。
上一页 [1] [2] [3] [4] [5] [6] 下一页