在vb中利用窗体结构设计定义一个限差类TolError,附带事件OverError,限差值设计为属性,由用户输入若干个高差(可正可负),计算其总的高差h,超过限差值则触发事件OverError。
时间: 2024-09-24 21:29:21 浏览: 50
在Visual Basic中,你可以创建一个名为TolError的自定义类(Class)来实现这个功能。首先,你需要定义类并包含必要的属性和方法:
```vb
Public Class TolError
' 定义限差值属性
Public Property Limit As Double
Private _tolerance As Double
' 属性设置器和获取器
Public Sub New(limit As Double)
_tolerance = limit
End Sub
Public Property Tolerance() As Double
Get
Return _tolerance
End Get
Set(value As Double)
If value >= 0 Then
_tolerance = value
Else
Throw New ArgumentException("限差值必须是非负数")
End If
End Set
End Property
' 计算高差总和的公共方法
Public Function CalculateTotalHeight(heights() As Double) As Double
Dim totalHeight As Double = 0
For Each height In heights
totalHeight += height
If Math.Abs(totalHeight) > Tolerance Then
RaiseEvent OverError(totalHeight)
End If
Next
Return totalHeight
End Function
' 事件声明
Public Event OverError(ByVal heightExceeded As Double)
End Class
```
在这个类中,`Limit`是一个属性,表示限差值;`_tolerance`是私有字段用于存储实际值。`New`构造函数接受限差值作为参数,并将其设置为属性。`CalculateTotalHeight`方法接收一数组的高差值,每次累加时检查是否超过限差值,如果超过,则触发`OverError`事件。
为了使用这个类,你可以在其他部分的代码中实例化它,并处理OverError事件:
```vb
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim tolError As New TolError(5.0) ' 设置限差值
Dim heights() As Double = {1.0, -2.5, 4.8} ' 用户输入的高差
Try
Dim result As Double = tolError.CalculateTotalHeight(heights)
MessageBox.Show($"总高差为: {result}")
Catch ex As ArgumentException
MessageBox.Show(ex.Message)
End Try
End Sub
Public Sub TolError_OverError(sender As Object, e As TolErrorEventArgs)
Dim exceededHeight = e.HeightExceeded
MessageBox.Show($"总高差超过了限差值: {exceededHeight}")
End Sub
```
阅读全文