VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > VB.net教程 >
  • vb.net教程之类的构造方法(函数)

类的构造方法(函数)(课本5.2)(相关vb.net教程)
1、构造方法是名称是new的过程,前面要以public说明。
2、同时可以定义多个同名的构造方法,只要它的参数个数或类型不同,此时称为重载。以增加构造方法的适用范围。
3、构造方法只在创建对象时由系统调用,不能在程序中人为调用。
修改上面“我的日期类”类,得到程序:类的构造方法,程序为:
Public Class mydate
    Public m_year, m_month, m_day As Integer
    Public Sub New()
        m_year = Microsoft.VisualBasic.Year(Now)
        m_month = Microsoft.VisualBasic.Month(Now)
        m_day = Microsoft.VisualBasic.Day(Now)
    End Sub
    Public Sub New(ByVal y As Integer, ByVal m As Integer, ByVal d As Integer)
        m_year = y : m_month = m : m_day = d
    End Sub
    Public Sub show()
        MsgBox(Str(m_year) + "-" + Str(m_month) + "-" + Str(m_day), MsgBoxStyle.OkOnly, "日期")
    End Sub
End Class
 
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim a As New mydate
        Dim b As New mydate(2008, 5, 1)
        a.show()
        b.show()
    End Sub
End Class
应用实例:用定义类的方法编程解决,任输入矩形的两边,求其周长与面积。
见,类的应用矩形问题,程序为:
Public Class juxing
    Public x, y As Integer
    Public Function p()
        p = 2 * (x + y)
    End Function
    Public Function area()
        area = x * y
    End Function
End Class
Public Class Form1
    Dim a As New juxing
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim pp, ss As Double
        pp = a.p
        ss = a.area
        Console.WriteLine("周长为:" + Str(pp))
        Console.WriteLine("面积为:" + Str(ss))
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        a.x = Val(TextBox1.Text)
        a.y = Val(TextBox2.Text)
    End Sub
End Class

相关教程