定义Shape类
Public Class Shape
Private mColor As String
'Color属性
Public Property Color() As String
Get
Return mColor
End Get
Set(ByVal value As String)
'简单的颜色格式验证,假设颜色格式为#RRGGBB
If value.Length = 7 AndAlso value.StartsWith("#") Then
Dim validChars As String = "0123456789ABCDEFabcdef"
Dim isValid As Boolean = True
For i As Integer = 1 To 6
If validChars.IndexOf(value(i)) = -1 Then
isValid = False
Exit For
End If
Next
If isValid Then
mColor = value
Else
'处理颜色格式不正确的情况,例如抛出异常或设置默认值
Throw New ArgumentException("Invalid color format.")
End If
Else
'处理颜色格式不正确的情况,例如抛出异常或设置默认值
Throw New ArgumentException("Invalid color format.")
End If
End Set
End Property
'抽象的Draw方法,子类必须实现
Public MustOverride Sub Draw(ByVal g As Graphics)
End Class
解释
- Color属性:使用
Private
变量mColor
来存储颜色值。在Set
访问器中进行颜色格式验证,要求颜色字符串长度为7且以#
开头,后续6位为十六进制字符。如果格式不正确,抛出ArgumentException
异常。
- Draw方法:定义为
MustOverride
,表示这是一个抽象方法,子类必须实现该方法来具体绘制图形。
圆形子类
Public Class Circle
Inherits Shape
Private mRadius As Integer
Private mX As Integer
Private mY As Integer
Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal radius As Integer)
mX = x
mY = y
mRadius = radius
End Sub
Public Overrides Sub Draw(ByVal g As Graphics)
Using brush As New SolidBrush(ColorTranslator.FromHtml(Me.Color))
g.FillEllipse(brush, mX - mRadius, mY - mRadius, mRadius * 2, mRadius * 2)
End Using
End Sub
End Class
解释
- 继承关系:
Circle
类继承自Shape
类,因此必须实现Shape
类中的抽象Draw
方法。
- Draw方法实现:根据
Circle
类的属性(圆心坐标mX
、mY
和半径mRadius
),使用Graphics
对象的FillEllipse
方法在指定位置绘制一个填充的圆形。颜色使用ColorTranslator.FromHtml
方法将存储的颜色字符串转换为Color
对象用于绘制。
矩形子类
Public Class Rectangle
Inherits Shape
Private mX As Integer
Private mY As Integer
Private mWidth As Integer
Private mHeight As Integer
Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer)
mX = x
mY = y
mWidth = width
mHeight = height
End Sub
Public Overrides Sub Draw(ByVal g As Graphics)
Using brush As New SolidBrush(ColorTranslator.FromHtml(Me.Color))
g.FillRectangle(brush, mX, mY, mWidth, mHeight)
End Using
End Sub
End Class
解释
- 继承关系:
Rectangle
类同样继承自Shape
类,所以也要实现Draw
方法。
- Draw方法实现:依据
Rectangle
类的属性(左上角坐标mX
、mY
以及宽度mWidth
和高度mHeight
),利用Graphics
对象的FillRectangle
方法绘制一个填充的矩形。颜色处理方式与Circle
类类似。