VB.Net Tutorial/Class Module/Structure — различия между версиями

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

Текущая версия на 15:55, 26 мая 2010

By value or by reference

<source lang="vbnet">Option Strict On Public Class YourClass

  Public Name As String
  Public GPA As Double

End Class Public Structure YourStructure

  Public Name As String
  Public GPA As Double

End Structure Public Class Test

  Public Shared Sub Main()
     Dim valueByRef As New YourClass()
     Dim valueByValue As New YourStructure()
     valueByRef.Name = "Jill"
     valueByRef.GPA = 92.3
     valueByValue.Name = "Jill"
     valueByValue.GPA = 92.3
     Dim ref2 As YourClass = valueByRef
     Dim value2 As YourStructure = valueByValue
     ref2.GPA += 2
     value2.GPA += 2
     Console.WriteLine("{0}"s GPA is: {1}", valueByRef.Name, valueByRef.GPA)
     Console.WriteLine("{0}"s GPA is: {1}", valueByValue.Name, valueByValue.GPA)
  End Sub

End Class</source>

Jill"s GPA is: 94.3
Jill"s GPA is: 92.3

Class Vs Structure in ByValue and ByRef

<source lang="vbnet">Imports System Public Enum Country

 US = 1
 CA = 2

End Enum

Public Class AClass

 Public Name As String
 Public Status As Country

End Class Public Structure AStruct

 Public Name As String
 Public Status As Country

End Structure Public Module Test

 Public Sub ChangeName_Obj_ByVal(ByVal details As AClass,ByVal NewName As String)
   details.Name = NewName
 End Sub
 Public Sub ChangeName_Obj_ByRef(ByRef details As AClass,ByVal NewName As String)
   details.Name = NewName
 End Sub
 Public Sub ChangeName_Struct_ByVal(ByVal details As AStruct,ByVal NewName As String)
   details.Name = NewName
 End Sub
 Public Sub ChangeName_Struct_ByRef(ByRef details As AStruct,ByVal NewName As String)
   details.Name = NewName
 End Sub
 Sub Main()
   Dim classInstance As AClass = New AClass()
   Dim structInstance As AStruct = New AStruct()
   classInstance.Name = "A"
   classInstance.Status = Country.CA
   structInstance.Name = "B"
   structInstance.Status = Country.CA
   Console.WriteLine("{0}, {1}", classInstance.Name, classInstance.Status)
   Console.WriteLine("{0}, {1}", structInstance.Name, structInstance.Status)
   Console.WriteLine()
   ChangeName_Obj_ByVal(classInstance, "AAAA")
   ChangeName_Struct_ByVal(structInstance, "BBBB")
  
   Console.WriteLine("{0},{1}", classInstance.Name, classInstance.Status)
   Console.WriteLine("{0},{1}", structInstance.Name, structInstance.Status)
   Console.WriteLine()
   ChangeName_Obj_ByRef(classInstance, "AAAA")
   ChangeName_Struct_ByRef(structInstance, "BBBB")
   Console.WriteLine("{0}, {1}", classInstance.Name, classInstance.Status)
   Console.WriteLine("{0}, {1}", structInstance.Name, structInstance.Status)
 End Sub

End Module</source>

A, CA
B, CA
AAAA,CA
B,CA
AAAA, CA
BBBB, CA

Define and use Structure

<source lang="vbnet">Structure CheckRecord

   Dim intCheckNumber As Integer
   Dim dteCheckDate As Date
   Dim sngCheckAmount As Single
   Dim strCheckPaidTo As String

End Structure public class Test

  public Shared Sub Main
       Dim udtCheck As CheckRecord
       "Add data to the structure.
       udtCheck.intCheckNumber = 275
       udtCheck.dteCheckDate = #9/12/2001#
       udtCheck.sngCheckAmount = 104.25
       udtCheck.strCheckPaidTo = "Gas Co."
       Console.WriteLine("CHECK INFORMATION")
       Console.WriteLine("Number: " & udtCheck.intCheckNumber)
       Console.WriteLine("Date: " & udtCheck.dteCheckDate)
       Console.WriteLine("Amount: " & udtCheck.sngCheckAmount)
       Console.WriteLine("Paid To: " & udtCheck.strCheckPaidTo)
  End Sub

End class</source>

CHECK INFORMATION
Number: 275
Date: 12/09/2001
Amount: 104.25
Paid To: Gas Co.

Define and use structure with modifier

<source lang="vbnet">Option Strict On Public Structure Coordinates

  Public x As Double
  Public y As Double

End Structure Public Module Test

  Public Sub Main()
     Dim coord As Coordinates " The structure as a whole
     
     coord.x = 10.2 " x member
     coord.y = 25.1 " y member
     Console.WriteLine(coord.ToString & ": x=" & coord.x & ", y=" & coord.y)
  End Sub

End Module</source>

Coordinates: x=10.2, y=25.1

Define Structure

<source lang="vbnet">Option Strict On

Imports System
    Public Structure Location
        Private x As Integer
        Private y As Integer
        Public Sub New(ByVal xCoordinate As Integer, ByVal yCoordinate As Integer)
            x = xCoordinate
            y = yCoordinate
        End Sub
        Public Property XValue( ) As Integer
            Get
                Return x
            End Get
            Set(ByVal Value As Integer)
                x = Value
            End Set
        End Property
        Public Property YValue( ) As Integer
            Get
                Return y
            End Get
            Set(ByVal Value As Integer)
                y = Value
            End Set
        End Property
        Public Overrides Function ToString( ) As String
            Return [String].Format("{0}, {1}", x, y)
        End Function
    End Structure
    Class Tester
        Public Shared Sub myFunc(ByVal loc As Location)
            loc.XValue = 50
            loc.YValue = 100
            Console.WriteLine("Loc1 location: {0}", loc)
        End Sub 
        Shared Sub Main( )
            Dim loc1 As New Location(200, 300)
            Console.WriteLine("Loc1 location: {0}", loc1)
            Dim loc2 As New Location( )
            Console.WriteLine("Loc2 location: {0}", loc2)
            myFunc(loc1)
            Console.WriteLine("Loc1 location: {0}", loc1)
        End Sub 
    End Class</source>
Loc1 location: 200, 300
Loc2 location: 0, 0
Loc1 location: 50, 100
Loc1 location: 200, 300

Structure

<source lang="vbnet">Structure Money

  Private centsAmount As Integer
  Public Sub New(ByVal amount As Double)
      Me.centsAmount = CInt(amount * 100)
  End Sub

End Structure Module MyModule

  Sub Main()
      Dim freebie As Money
      Dim carPrice As Money = New Money(3.95)
  End Sub

End Module</source>

structure implements interface

<source lang="vbnet">Imports System Module MyModule

 Sub Main()
   Dim salaries(4) As Salary
   salaries(0) = New Salary(9)
   salaries(1) = New Salary(4)
   salaries(2) = New Salary(8)
   salaries(3) = salaries(2)
   salaries(4) = New Salary(6)
   Console.WriteLine("Unsorted array:")
   Dim salary As Salary
   For Each salary In salaries
     Console.WriteLine("{0}", salary)
   Next
   Array.Sort(salaries)
   Console.WriteLine(vbCrLf & "Sorted array:")
   For Each salary In salaries
     Console.WriteLine("{0}", salary)
   Next
 End Sub

End Module Structure Salary

 Implements IComparable
 Private value As Integer
 Public Sub New(ByVal amount As Double)
   Me.value = CInt(amount * 100)
 End Sub
 Public Function CompareTo(ByVal other As Object) As Integer Implements IComparable.rupareTo
   Dim m2 As Salary = CType(other, Salary)
   If Me.value < m2.value Then
     Return -1
   ElseIf Me.value = m2.value Then
     Return 0
   Else
     Return +1
   End If
 End Function
 Public Overrides Function ToString() As String
   Return Me.value
 End Function

End Structure</source>

Unsorted array:
900
400
800
800
600
Sorted array:
400
600
800
800
900

Use Structure as Function parameter

<source lang="vbnet">public Structure CustomerBalance

   Dim decBalSavings As Decimal
   Dim decBalChecking As Decimal

End Structure

public class Test

  public Shared Sub Main
       Dim udtBalance As CustomerBalance
       
       udtBalance = GetCustomerBalance(1)
       Console.WriteLine(udtBalance.decBalChecking)
       Console.WriteLine(udtBalance.decBalSavings)
  End Sub
  Shared Function GetCustomerBalance(ByVal intCustomerID As Integer) As CustomerBalance
       Dim udtBalance As CustomerBalance
       udtBalance.decBalChecking = CDec(1000 + 4000 * Rnd())
       udtBalance.decBalSavings = CDec(1000 + 15000 * Rnd())
       Return udtBalance
   End Function
  

End class</source>

3822.19
9001.36

Use With and Structure

<source lang="vbnet">Imports System.Collections Structure Person

   Dim strLastName As String
   Dim strFirstName As String
   Dim strPhone As String
   Dim strEMail As String

End Structure

public class Test

  public Shared Sub Main
       Dim alPersons As New ArrayList
       Dim udtPerson As New Person
       "Add the first person.
       With udtPerson
           .strLastName = "S"
           .strFirstName = "J"
           .strPhone = "5"
           .strEMail = "j@s.ru"
       End With
       alPersons.Add(udtPerson)
       "Add the second person.
       With udtPerson
           .strLastName = "J"
           .strFirstName = "S"
           .strPhone = "5"
           .strEMail = "s@s.ru"
       End With
       alPersons.Add(udtPerson)
       "Create the third person.
       With udtPerson
           .strLastName = "J"
           .strFirstName = "K"
           .strPhone = "5"
           .strEMail = "k@s.ru"
       End With
       "Insert the third person, but first check if they already exists.
       If Not alPersons.Contains(udtPerson) Then
           alPersons.Insert(1, udtPerson)
       End If
       "Remove the first person.
       alPersons.RemoveAt(0)
       "Display the array list values.
       Console.WriteLine("The array list contains " & alPersons.Count & " elements.")
       For Each udtPerson In alPersons
           Console.WriteLine("NAME: " & udtPerson.strFirstName & " " & udtPerson.strLastName)
       Next udtPerson
  End Sub

End class</source>

The array list contains 2 elements.
NAME: K J
NAME: S J