vb.net - 如何在 VS 中运行独立的 vb.net 类代码
问题描述
Imports System.Windows.Forms
Class CDay
Inherits Object
Private mMonth As Integer ' 1-12
Private mDay As Integer ' 1-31 based on month
Private mYear As Integer ' any year
' constructor confirms proper value for month, then calls
' method CheckDay to confirm proper value for day
Public Sub New(ByVal monthValue As Integer, _
ByVal dayValue As Integer, ByVal yearValue As Integer)
' ensure month value is valid
If (monthValue > 0 AndAlso monthValue <= 12) Then
mMonth = monthValue
Else
mMonth = 1
Dim errorMessage As String = _
"Month invalid. Set to month 1."
MessageBox.Show(errorMessage, "", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
mYear = yearValue
mDay = CheckDay(dayValue) ' validate day
End Sub ' New
' confirm proper day value based on month and year
Private Function CheckDay(ByVal testDayValue As Integer) _
As Integer
Dim daysPerMonth() As Integer = _
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
If (testDayValue > 0 AndAlso _
testDayValue <= daysPerMonth(mMonth)) Then
Return testDayValue
End If
' check for leap year in February
If (mMonth = 2 AndAlso testDayValue = 29 AndAlso _
mYear Mod 400 = 0 OrElse mYear Mod 4 = 0 AndAlso _
mYear Mod 100 <> 0) Then
Return testDayValue
Else
' inform user of error
Dim errorMessage As String = _
"day " & testDayValue & "invalid. Set to day 1. "
MessageBox.Show(errorMessage, "", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Return 1 ' leave object in consistent state
End If
End Function ' CheckDay
' create string containing month/day/year format
Public Function ToStandardString() As String
Return mMonth & "/" & mDay & "/" & mYear
End Function ' ToStandardString
End Class
我从我正在学习的一本书中获得了上述独立的 vb.net 代码(我是 VB.net 的初学者)。如何在 Visual Studio 中运行它?我应该将此代码放在一个模块中(但是,下面的源代码中没有提到模块),还是放在 Windows 窗体中?我很困惑。请帮忙。
图 8.8:CDay.vb 封装了月、日和年。
解决方案
创建一个 WinForms 项目。CDay
使用“项目”菜单或右键单击“解决方案资源管理器”中的项目并选择“添加”,将一个名为的类添加到您的项目中。将该代码复制到类代码文件中并构建您的项目。恭喜!现在,您的项目中有一个CDay
类。您现在可以声明变量并创建该类型的实例,就像您为任何其他类型所做的那样。例如,您可以处理 a 的Click
事件Button
,创建CDay
该类的一个实例,然后显示它的值。
推荐阅读
- javascript - 为什么这个导出的 Gridfs 函数不能正确执行?
- c# - Resources.load 带有可编写脚本的对象
- sql - Redshift 的月数保留队列计算问题
- html - 如何使用变量值作为 gsp 页面上 HTML 元素的 id?
- linux - 尝试同时测试大于和小于时出现太多参数错误
- javascript - 基于模板和用户输入以编程方式创建新的 HTML 页面
- asp.net-mvc - 如何在我的网站上正确显示图像?
- c# - 我可以对将重试的瞬时错误禁用 EF Core 错误日志记录吗?
- javascript - 简单的 JQuery 滑动效果不同步
- c# - 在 dockerized Spa 应用程序中构建 webhost 需要很长时间