你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
VB.Net中文教程(1) 类别与封装性(4)
 

'ex07.bas
'Some Error Here!
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms
'-----------------------------------------
Class Tree
Private varity As String
Private age As Integer
Private height As Single
End Class
'-----------------------------------------
Public Class Form1
Inherits System.WinForms.Form

Public Sub New()
MyBase.New()
Form1 = Me
'This call is required by the Win Form Designer.
InitializeComponent()
'TODO: Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Public Overrides Sub Dispose()
MyBase.Dispose()
components.Dispose()
End Sub
#Region " Windows Form Designer generated code "
.......
#End Region
Public Sub Form1_Click( ByVal sender As Object, ByVal
e As System.EventArgs)
Dim a As New Tree()
a.height = 2.1
MessageBox.Show("height = " + str(a.height))
End Sub
End Class

此程序将原来的Public专用字改为Private﹐对Tree类别之资料成员采取严格之保护措施。Public 与Private之区别为──
Public 表示此类别外之程序可来存取资料成员。
Private 表示此类别外之程序绝无法直接存取资料成员﹐只有程序成员才能存取资料成员。

所以﹐计算机看到指令── a.height = 2.1,因Tree类别采取严格保护措施(private)﹐则Form1_Click()程序不能使用height变量名称。所以指令── a.height = 2.1错了。也许您问道﹕这样岂不是无法存取类别内之资料成员吗﹖答案是﹕「类别内之程序成员(Member Function) 可存取资料成员﹐而类别外之程序能藉程序成员代之存取资料成员。」

图1、类别之沟通管道──程序成员

这如同﹐引信管才能引起炸弹内之化学药品爆炸﹐人们只能经由引信管引爆之﹐让人们觉得使用炸弹既安全又简单。同样地﹐对象经由程序成员和外界沟通﹐可减少外界无意中破坏对象内之资料(无意中引爆炸弹)。例如﹕

'ex08.bas
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms
'--------------------------------------------------
Class Tree
Private varity As String
Private age As Integer
Private height As Single
Public Sub input(ByVal hei As Single)
height = hei
End Sub
End Class
'--------------------------------------------------
Public Class Form1
Inherits System.WinForms.Form

Public Sub New()
MyBase.New()
Form1 = Me
'This call is required by the Win Form Designer.
InitializeComponent()
'TODO: Add any initialization after the InitializeComponent() call
End Sub

'Form overrides dispose to clean up the component list.
Public Overrides Sub Dispose()
MyBase.Dispose()
components.Dispose()
End Sub
#Region " Windows Form Designer generated code "
.........
#End Region
Protected Sub Form1_Click( ByVal sender As Object, ByVal
e As System.EventArgs)
Dim a As New Tree()
a.input(2.1)
MessageBox.Show("OK")
End Sub
End Class

将input()摆在Tree类别中﹐为Tree之程序成员﹐它能存取资料成员height之值。把input()程序宣告为Public表示类别外之程序可藉来呼叫它﹐其呼叫格式为──

简单规则是﹕
Public 表示授权给外界之程序藉由此格式呼叫程序成员。

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089