‘ 一、类模块代码
‘ 类名: clsWire
‘ 包含8个参数、2个方法、1个事件
Option Explicit
‘ —————————-
‘ 1. 定义私有变量(8个参数)
‘ —————————-
Private pMaterial As String ‘ 材料
Private pLength As Double ‘ 长度
Private pDiameter As Double ‘ 直径
Private pVoltage As Double ‘ 电压
Private pCurrent As Double ‘ 电流
Private pResistance As Double ‘ 电阻
Private pTemperature As Double ‘ 温度
Private pIsInsulated As Boolean ‘ 是否有绝缘层
‘ —————————-
‘ 2. 定义事件
‘ —————————-
Event StatusChanged(ByVal Message As String)
‘ —————————-
‘ 类初始化(设置默认值)
‘ —————————-
Private Sub Class_Initialize()
pMaterial = “Copper” ‘ 默认材料为铜
pLength = 0
pDiameter = 0
pVoltage = 0
pCurrent = 0
pResistance = 0
pTemperature = 25 ‘ 默认温度25°C
pIsInsulated = False
End Sub
‘ —————————-
‘ 属性定义(8个参数)
‘ —————————-
Public Property Get Material() As String
Material = pMaterial
End Property
Public Property Let Material(ByVal Value As String)
pMaterial = Value
End Property
Public Property Get Length() As Double
Length = pLength
End Property
Public Property Let Length(ByVal Value As Double)
pLength = Value
End Property
Public Property Get Diameter() As Double
Diameter = pDiameter
End Property
Public Property Let Diameter(ByVal Value As Double)
pDiameter = Value
End Property
Public Property Get Voltage() As Double
Voltage = pVoltage
End Property
Public Property Let Voltage(ByVal Value As Double)
pVoltage = Value
End Property
Public Property Get Current() As Double
Current = pCurrent
End Property
Public Property Let Current(ByVal Value As Double)
pCurrent = Value
End Property
Public Property Get Resistance() As Double
Resistance = pResistance
End Property
Public Property Let Resistance(ByVal Value As Double)
pResistance = Value
End Property
Public Property Get Temperature() As Double
Temperature = pTemperature
End Property
Public Property Let Temperature(ByVal Value As Double)
pTemperature = Value
End Property
Public Property Get IsInsulated() As Boolean
IsInsulated = pIsInsulated
End Property
Public Property Let IsInsulated(ByVal Value As Boolean)
pIsInsulated = Value
End Property
‘ —————————-
‘ 方法1:计算功率
‘ —————————-
Public Function CalculatePower() As Double
CalculatePower = pVoltage * pCurrent ‘ P = V * I
RaiseEvent StatusChanged(“功率计算完成: ” & CalculatePower & “W”)
End Function
‘ —————————-
‘ 方法2:检查安全性
‘ —————————-
Public Sub CheckSafety()
Dim msg As String
If pTemperature > 80 Then
msg = “警告:温度过高(” & pTemperature & “°C)!”
ElseIf pCurrent > 10 Then
msg = “警告:电流超过安全阈值!”
Else
msg = “系统状态正常”
End If
RaiseEvent StatusChanged(msg) ‘ 触发事件
End Sub
‘ 二、调用
‘ 在窗体代码中:
Dim WithEvents myWire As clsWire ‘ 必须使用 WithEvents 捕获事件
Private Sub Form_Load()
Set myWire = New clsWire
myWire.Voltage = 220
myWire.Current = 5
myWire.Temperature = 75
‘ 调用方法
Debug.Print “功率:” & myWire.CalculatePower()
myWire.CheckSafety
End Sub
‘ 处理事件
Private Sub myWire_StatusChanged(ByVal Message As String)
MsgBox Message, vbInformation, “导线状态”
End Sub