在vb里,利用控制台应用程序,定义一个限差类TolError,附带事件OverError,限差值设计为属性,由用户选择输入几个高差,在用户输入若干个高差(可正可负)后,计算其总的高差h,超过限差值则触发事件OverError。
时间: 2024-09-27 10:04:21 浏览: 32
在VB中,你可以创建一个名为TolError的控件类,用于管理高差的限差和异常处理。首先,定义这个类并包含一个表示限差的属性,例如`m_Tolerance`。然后,为它添加一个自定义事件如`OverError`,当高差总和超过限差值时触发。
```vb
Public Class TolError
' 定义限差值属性
Private m_Tolerance As Double
Public Property Tolerance() As Double
Get
Return m_Tolerance
End Get
Set(value As Double)
If value >= 0 Then
m_Tolerance = value
Else
Throw New ArgumentException("限差值必须是非负数")
End If
End Set
End Property
' 定义高差列表
Private m_HighDifferences As List(Of Double)
' 自定义事件
Public Event OverError(highDifference As Double)
Sub AddHighDifference(ByVal highDifference As Double)
m_HighDifferences.Add(highDifference)
CalculateTotalAndCheckLimit()
End Sub
Private Sub CalculateTotalAndCheckLimit()
Dim totalDifference As Double = m_HighDifferences.Sum()
If totalDifference > Tolerance Then
RaiseEvent OverError(totalDifference)
End If
End Sub
End Class
```
要使用这个类,你需要在控制台程序中实例化它,并通过`AddHighDifference`方法添加高差,当`OverError`事件触发时,可以在外部代码中处理:
```vb
Module Module1
Sub Main()
Dim tolError As New TolError
tolError.Tolerance = 50.0 ' 设置限差值
Console.WriteLine("请输入高差(输入-1结束):")
While True
Dim input As String = Console.ReadLine()
If input = "-1" Then Exit While
Try
Dim difference As Double = Convert.ToDouble(input)
tolError.AddHighDifference(difference)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End While
Console.WriteLine("高差总和超过了限差值吗? " & (If(tolError.HasEventOccurred(OverError), "是", "否")))
End Sub
End Module
```
阅读全文