VB.NETを咥えてWindows.Formsをつつく4-継承1。親の仕様を無視するな!逃走ボタン。
Imports System
Imports System.Text
Imports System.Drawing
Imports System.Windows.Forms
Public Class FormProgram
Public Shared Sub Main()
Dim frm As PiyoForm = Nothing
For i As Integer = 0 To 100
'ピヨフォームを用意するピヨ♪
frm = New PiyoForm(i)
frm.Show()
'逃げるボタンを追加♪
Dim btn As EscapingButton = New EscapingButton()
frm.Controls.Add(btn)
Next
frm.BackColor = Color.Red
Application.Run(frm)
End Sub
End Class
Imports System.Drawing
Imports System.Windows.Forms
'逃走ボタン
Public Class EscapingButton
Inherits Button
Private rand As Random
Sub New()
rand = New Random()
Me.Text = "私をクリックしないで!"
Me.Width = Me.CreateGraphics().MeasureString(Me.Text & _
"あ", Me.Font).ToSize().Width
End Sub
Protected Overrides Sub OnClick(ByVal e As System.EventArgs)
MyBase.OnClick(e)
'クリックされたら消える
MessageBox.Show("ぐはあっ!やられた・・・")
Me.Dispose()
End Sub
Protected Overrides Sub OnMouseHover(ByVal e As System.EventArgs)
MyBase.OnMouseHover(e)
'クリックされないように逃げる
Dim x As Integer = rand.Next(0, Me.Width + 100)
Dim y As Integer = rand.Next(0, Me.Height + 100)
Me.Location = New Point(x, y)
'画面上をはみ出た場合戻る
If Not Me.Parent Is Nothing Then
Dim flag As Boolean = False
If x >= Me.Parent.Width Then
x = rand.Next(0, Me.Parent.Width)
flag = True
End If
If y >= Me.Parent.Height Then
y = rand.Next(0, Me.Parent.Height)
flag = True
End If
If flag = True Then
Me.Location = New Point(x, y)
End If
End If
End Sub
End Class
こんな具合に継承を禁止されていないクラスは何でも継承できるピヨ。じゃあ、このサンプルコードを動かそう!あっ!丁度いい時に人が来た。ドリィちゃんちょっとこれ見て♪
ドリィちゃん「何この悪趣味な画面?!それに何かしらこのボタン・・・そんなこと言われたらクリックしたくなるじゃないのぉ。えぃ!あっ逃げられたぁ!こしゃくなぁぁーえぃっ!えいっ!えいっ!よしやったわよ!あれ?何でボタンなのにクリックしたら消えるの?」
ボクオリジナルの逃走ボタンだからさ♪
ドリィちゃん「???あのねぇ。ボタンはクリックされるためにあるんだから、このボタン意味ないわよ!」
が~ん!
ドリィちゃん「ばかぁ。もうまた変なものつくてぇ。まぁ、面白いけどね(ぼそ)論理的整合性をコンパイラはチェックしてくれないから、みんな注意してね❤親クラスの仕様をじっくり調べて、注意して子クラスを実装してね❤」
今回の教訓:子クラスを実装する時、親クラスの役割をよく考えて論理的整合性が崩れないようにしよう。
※適切な表現にするために記事を修正しました。