6.Inherit ก๊อป มัน เลย

posted on 09 Jul 2009 17:40 by inet03  in Vb-Wpf-Lerning

คำอธิบายที่ต้องปีนบรรไดอ่าน : คือการสืบทอดคลาส
คำอธิบายแบบชาวบ้านๆ : คือการก๊อปคลาสชาวบ้านเขามานั่นแหละ

Class A
Public z, y As New Integer
End Class

Class B
Inherit A
Public x As New Integer
End Class

Dim bb As New B
bb.z = 0 : bb.y = 1 : bb.x = 2
'bb หรือคลาส b สามารถเรียก z กับ y มาได้เพราะก๊อปมาจากคลาส A

โดยพื้นฐานแล้วคำสั่ง Inherit นั้นเรียกได้ว่าแทบไร้ประโยชน์อย่างแรง
เพราะมีคำสั่งที่จะแทนที่คำสั่งนี้ได้มากมายเหลือเกิน

สำหรับผู้ที่เห็นด้วยกับประโยคด้านบนนี้ละก็
ผมบอกได้เลยว่าคุณยังไม่เคยเขียนเข้าเขตวิกฤติครับ
มาดูตัวอย่างกันครับ

กรณีตัวอย่าง WPF :
เป็นการเรียกใช้ปุ่มกด(Button : zItem) แบบไม่ประกาศชื่อ
เมื่อกดแล้วให้ขึ้น Messagebox บอกตัวเลขของปุ่มนั้น
แต่ว่าคลาสของปุ่มมีการเรียกใช้อยู่ก่อนแล้ว ซึ่งเมื่อกดแล้วก็จะเปลี่ยนสี

Class Form
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

For i = 0 to 10
 
WarpPanel.Childen.Add(New zItem(Height,Width,i.ToString))
 
Next
End Sub
End Class

Partial Public Class zItem

Public Sub New()
MyBase.New()
Me.InitializeComponent()
End Sub

Public Value As String = ""

Public Sub New( _
ByVal iHeight As Double, ByVal iWidth As Double, ByVal iValue As String, _
ByRef Action As System.Windows.RoutedEventHandler)

InitializeComponent()
With Me
.Height = iHeight
.Width = iWidth
.Value = iValue
.AddHandler(MouseLeftButtonUpEvent, Action)
End With

End Sub
End Class

ปัญหาก็คือเราจะใช้ค่า i.Tostring ที่เก็บไว้ในปุ่มได้อย่างไร ในเมื่อเราไม่รู้ชื่อปุ่มนั้นด้วยซ้ำ
ตรงนี้แหละครับที่ Inherit เข้ามาเป็นพระเอกขี่ม้าขาว

Public Class XItem
Inherit zItem

Public Sub New(ByVal iHeight As Double, _
ByVal iWidth As Double, ByVal iValue As String)

InitializeComponent()

With Me
.Height = iHeight
.Width = iWidth
.Value = iValue
End With

End Sub

Private Sub MouseClick( _
ByVal sender As Object,ByVal e As System.Windows.RoutedEventArgs) _
Handler MouseClick

Messagebox.Show(Value)

End Sub
End Class

ถ้าตัวอย่างนี้ทำให้งงหนักกว่าเดิมต้องขออภัย ผมนึกที่ง่ายกว่านี้ไม่ออกแล้ว@_@

Comment



smilebig smileopen-mounthed smileconfused smilesad smileangry smiletonguequestionembarrassedsurprised smilewinkdouble winkcry

Tweet