VB.Net中文教程(4) 母子对象关系(2)

页面导航:首页 > 软件编程 > vb.net > VB.Net中文教程(4) 母子对象关系(2)

VB.Net中文教程(4) 母子对象关系(2)

来源: 作者: 时间:2016-02-05 12:32 【

Class MyRoom Inherits Room Private rd As New Desk() Public Sub New() rSize

 

 

Class MyRoom

   Inherits Room

   Private rd As New Desk()

  

   Public Sub New()

       rSize = 100

   End Sub

   Public Sub Show()

       MessageBox.Show("Room Size: " + str(rSize))

       MessageBox.Show("Desk Size: " + str(rd.GetSize()))

   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 r As New MyRoom()

       r.Show()

   End Sub

End Class

 

其对象之建造过程为﹕

Step 1: 指令──

               Dim r As New MyRoom()

呼叫MyRoom()建构者New()。它再呼叫Room()建构者New()将Room部分建好。

 

Step 2: 执行指令──

               Private rd As New Desk()

      呼叫Desk建构者New()﹐建好Desk子对象。此时会执行指令── 

               dSize = Room.GetMother().GetSize() * 0.18

 

Step 3: MyRoom建构者New() 继续将母对象建完成。

       此时会执行指令──  rSize=100

 

其中,GetSize()程序会取出rSize 值﹐但那时还未执行rSize=100 指令﹐那来

rSize 值呢﹖所以出问题了。此程序可能输出如下错误结果﹕

                  Room Size: 100

                  Desk Size: 0

      

如何解决上述问题呢﹖常见方法是﹕

 

   把会出问题的指令﹐从建构者

Tags:

文章评论


<