首页 > 解决方案 > 如何在 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 封装了月、日和年。

标签: vb.net

解决方案


创建一个 WinForms 项目。CDay使用“项目”菜单或右键单击“解决方案资源管理器”中的项目并选择“添加”,将一个名为的类添加到您的项目中。将该代码复制到类代码文件中并构建您的项目。恭喜!现在,您的项目中有一个CDay类。您现在可以声明变量并创建该类型的实例,就像您为任何其他类型所做的那样。例如,您可以处理 a 的Click事件Button,创建CDay该类的一个实例,然后显示它的值。


推荐阅读