VB.Net Tutorial/Class Module/Constructor

Материал из VB Эксперт
Перейти к: навигация, поиск

Call member method in constructor

Option Strict On
Public Class Counters
   Dim ctr As Integer
   Public Sub New()
      For ctr = 1 to 20
         DoSomething()
      Next
   End Sub

   Public Sub DoSomething()
      Console.WriteLine(Me.ctr)
   End Sub
End Class
Public Module modMain
   Public Sub Main()
      Dim obj As New Counters()
   End Sub
End Module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Class with constructor

Option Strict On
 Imports System
 Public Class Time
    " Private variables
    Private Year As Integer
    Private Month As Integer
    Private mDate As Integer
    Private Hour As Integer
    Private Minute As Integer
    Private Second As Integer
    " Public methods
    Public Sub DisplayCurrentTime( )
         System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, mDate, Year, Hour, Minute, Second)
    End Sub "DisplayCurrentTime
    " Constructor
    Public Sub New(ByVal theYear As Integer,ByVal theMonth As Integer, _
                   ByVal theDate As Integer, ByVal theHour As Integer, _
                   ByVal theMinute As Integer, ByVal theSecond As Integer)
       Year = theYear
       Month = theMonth
       mDate = theDate
       Hour = theHour
       Minute = theMinute
       Second = theSecond
    End Sub
 End Class "Time
 Module Module1
    Sub Main( )
       Dim timeObject As New Time(2005, 3, 25, 9, 35, 20)
       timeObject.DisplayCurrentTime( )
    End Sub
 End Module
3/25/2005 9:35:20

Constructor Chain

Public Class YourClass
  Public Address as String = "Default"
  Public City As String = "Default"
  Sub New()
    MyBase.New()
    Console.WriteLine("YourClass Created")
  End Sub
  Sub New(A as String, C As String)
    Me.New()
    Address = A
    City = C
    Console.WriteLine("YourClass.Address and Set")
  End Sub
End Class
Module Test
  Sub Main()
    Dim SL As New YourClass("123 First Street", "Somewhere")  
  End Sub
End Module
YourClass Created
YourClass.Address and Set

constructor inheriting

Public Class Address
  Private MyState as String = "DEFAULT"
  Sub New()
    MyBase.New()
    Console.WriteLine("Address Created")
  End Sub
  Public Property State As String
    Get
      Return MyState
    End Get
    Set(Value As String)
      MyState = Value
    End Set
  End Property
End Class
Public Class MyAddress
  Inherits Address
  Private MyAddress as String
  Sub New()
    MyBase.New()
    Console.WriteLine("MyAddress Created")
  End Sub
  Public Property Address as String
    Get
      Return MyAddress
    End Get
    Set(Value As String)
      MyAddress = Value
    End Set
  End Property
End Class
Module Test
  Sub Main()
    Dim SL As New MyAddress() 
    SL.State = "CANADA"
    SL.Address = "123"
  End Sub
End Module
Address Created
MyAddress Created

Constructors in three levels

Class A
    Public Sub New()
        Console.WriteLine("In class A constructor")
    End Sub
End Class
Class B
    Inherits A
    Public Sub New()
        Console.WriteLine("In class B constructor")
    End Sub
End Class
Class C
    Inherits B
    Public Sub New()
        Console.WriteLine("In class C constructor")
    End Sub
End Class
Module Module1
    Sub Main()
        Dim objSample As New C()
    End Sub
End Module
In class A constructor
In class B constructor
In class C constructor

Constructor with Optional parameter

Public Class Point
  Private MX as Integer
  Private MY as Integer
  Public Sub New(Optional X As Integer = 0, Optional Y As Integer = 0)
    MX = X
    MY = Y
  End Sub
  Public Overrides Function ToString() As String 
    Return "(" & MX & "," & MY & ")"
  End Function
End Class
Module OptionalPoint
  Sub Main
    Dim P1 As New Point()
    Console.WriteLine(P1.ToString())
    Dim P2 As New Point(1, 1)
    Console.WriteLine(P2.ToString())
    Dim P3 As New Point(, 1)
    Console.WriteLine(P3.ToString())
    Dim P4 As New Point(9, )
    Console.WriteLine(P4.ToString())
  End Sub
End Module
(0,0)
(1,1)
(0,1)
(9,0)

Copy constructor

Option Strict On
 Imports System
 Public Class Time
    " Private variables
    Private Year As Integer
    Private Month As Integer
    Private mDate As Integer
    Private Hour As Integer
    Private Minute As Integer
    Private Second As Integer = 30
    " Public methods
    Public Sub DisplayCurrentTime( )
         System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", _
             Month, mDate, Year, Hour, Minute, Second)
    End Sub "DisplayCurrentTime
    Public Sub New( _
    ByVal theYear As Integer, _
    ByVal theMonth As Integer, _
    ByVal theDate As Integer, _
    ByVal theHour As Integer, _
    ByVal theMinute As Integer)
       Year = theYear
       Month = theMonth
       mDate = theDate
       Hour = theHour
       Minute = theMinute
    End Sub
    Public Sub New(existingObject As Time)
       Year = existingObject.Year
       Month = existingObject.Month
       mDate = existingObject.mDate
       Hour = existingObject.Hour
       Minute = existingObject.Minute
       Second = existingObject.Second
    End Sub
 End Class "Time
 Module Module1
    Sub Main( )
       Dim timeObject As New Time(2005, 3, 25, 9, 35)
       Dim t2 As New Time(timeObject)
       timeObject.DisplayCurrentTime( )
       t2.DisplayCurrentTime( )
    End Sub
 End Module
3/25/2005 9:35:30
3/25/2005 9:35:30

Default constructor

Imports System
Module Test
  Sub Main()
    Dim p1 as New Point()
    Dim p2 as New Point()
    p2.Y = 100
    p2.X = 100
    Console.WriteLine(p1)
    Console.WriteLine(p2)
  End Sub
End Module
Class Point
  Public X as Integer
  Public Y as Integer
  Public Overrides Function ToString() as String
    Return("(" & X & "," & Y & ")")  
  End function
End Class
(0,0)
(100,100)

Empty constructor

Imports System
Module Test
  Sub Main()
    Dim p1 as New Point()
    Dim p2 as New Point(100,100) 
    Console.WriteLine(p1)
    Console.WriteLine(p2)
  End Sub
End Module
Class Point
  Private X as Integer
  Private Y as Integer
  Sub New()
  End Sub
  Sub New(x as integer, y as Integer)
    Me.X = x
    Me.Y = y
  End Sub
  Public Overrides Function ToString() as String
    Return("(" & X & "," & Y & ")")  
  End function
End Class
(0,0)
(100,100)

Inheriting Constructors

Public Class Tester
    Public Shared Sub Main
        Dim objJohn As New John("Walking...")
        objJohn.Walk()
    End Sub
End Class
Public Class Person
    Private Text As String
    Public Sub New(ByVal Message As String)
        Text = Message
    End Sub
    Public Sub Walk()
        Console.WriteLine(Text)
    End Sub
End Class
Class John
    Inherits Person
    Public Sub New(ByVal Message As String)
        MyBase.New(Message)
    End Sub
End Class
Walking...

Overloaded constructors

Module Tester
   Sub Main()
      " use overloaded constructors
      Dim time1 As New MyTime()
      Dim time2 As New MyTime(2)
      Dim time3 As New MyTime(21, 34)
      Dim time4 As New MyTime(12, 25, 42)
      Dim time5 As New MyTime(27, 74, 99)
      Dim time6 As New MyTime(time4) " use time4 as initial value
      Console.WriteLine(time1.ToUniversalString() )
      Console.WriteLine(time2.ToUniversalString() )
      Console.WriteLine(time3.ToUniversalString())
      Console.WriteLine(time4.ToUniversalString())
      Console.WriteLine(time5.ToUniversalString())
      Console.WriteLine(time6.ToUniversalString())
   End Sub " Main
End Module 
Class MyTime
   Inherits Object
   Private mHour As Integer   " 0 - 23
   Private mMinute As Integer " 0 - 59
   Private mSecond As Integer " 0 - 59
   Public Sub New()
      SetTime()
   End Sub " New
   Public Sub New(ByVal hourValue As Integer)
      SetTime(hourValue)
   End Sub " New
   Public Sub New(ByVal hourValue As Integer, _
      ByVal minuteValue As Integer)
      SetTime(hourValue, minuteValue)
   End Sub " New
   Public Sub New(ByVal hourValue As Integer, _
      ByVal minuteValue As Integer, ByVal secondValue As Integer)
      SetTime(hourValue, minuteValue, secondValue)
   End Sub " New
   Public Sub New(ByVal timeValue As MyTime)
      SetTime(timeValue.mHour, timeValue.mMinute, timeValue.mSecond)
   End Sub " New
   Public Sub SetTime(Optional ByVal hourValue As Integer = 0, _
      Optional ByVal minuteValue As Integer = 0, _
      Optional ByVal secondValue As Integer = 0)
      If (hourValue >= 0 AndAlso hourValue < 24) Then
         mHour = hourValue
      Else
         mHour = 0
      End If
      If (minuteValue >= 0 AndAlso minuteValue < 60) Then
         mMinute = minuteValue
      Else
         mMinute = 0
      End If
      If (secondValue >= 0 AndAlso secondValue < 60) Then
         mSecond = secondValue
      Else
         mSecond = 0
      End If
   End Sub " SetTime
   Public Function ToUniversalString() As String
      Return String.Format("{0}:{1:D2}:{2:D2}", _
         mHour, mMinute, mSecond)
   End Function " ToUniversalString
End Class
0:00:00
2:00:00
21:34:00
12:25:42
0:00:00
12:25:42

Private Constructor

Public Class Util
  Private Sub New()
  End Sub
  Public Shared Function QuoteIt(ToQuote as String, Author As String) As String
    Return ToQuote + "  - " + Author
  End Function
  
  Public Shared Function UpperLower(ToChange as String) As String
    Dim i as Integer
    Dim stringBuilder as New Text.StringBuilder(ToChange)
    For i = 0 To ToChange.Length - 1
        stringBuilder.Chars(i) = Char.ToUpper(stringBuilder.Chars(i))
    Next
    Return stringBuilder.ToString()
  End Function
End Class
Module Test
  Sub Main
    Console.WriteLine(Util.QuoteIt("A", "B"))
    Console.WriteLine(Util.UpperLower("AAaa"))
  End Sub
End Module
A  - B
AAAA

Shared Constructor

Public Class YourClass
  Private Shared ID as Integer = 10
  Public Shared ReadOnly Property CurrentID as Integer
    Get
      Return ID
    End Get
  End Property
  Public Shared Function GetID() as Integer
    ID += 1
    Return ID
  End Function
  Shared Sub New()
    Console.WriteLine("Before init: " & ID)
    ID = 100
    Console.WriteLine("After init: " & ID)
  End Sub
End Class
Module Test
  Sub Main()
    Dim CountValue As Integer
    For CountValue = 1 to 10
      Console.WriteLine(YourClass.GetID())
    Next
  End Sub
End Module
Before init: 10
After init: 100
101
102
103
104
105
106
107
108
109
110