VB.Net Tutorial/Class Module/Property — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:55, 26 мая 2010
Содержание
- 1 Change value in Property getter
- 2 Class with a property that performs validation
- 3 Convert data type in property set
- 4 Default Property
- 5 Define and use a Property
- 6 Do calculation in Property getter
- 7 Do data check in property set
- 8 Friend Property
- 9 Loop through two dimensional array with GetUpperBound and GetLowerBound
- 10 MultiKey Properties
- 11 Overloaded Properties
- 12 Properties with Getter and Setter
- 13 Readable and Writable
- 14 ReadOnly property
- 15 Shared Properties
- 16 Shared variable and Shared Property
- 17 Single Indexed Property
- 18 Throw Exception in Property setting
- 19 Two properties
- 20 Use Property to set private data
Change value in Property getter
<source lang="vbnet">Imports System Module Test
Sub Main() Dim p as Point = New Point() Console.WriteLine("(" & p.X & "," & p.Y & ")") Try p.X = -100 p.Y = -100 Catch e as ArgumentOutOfRangeException Console.WriteLine(e.Message) End Try Console.WriteLine("(" & p.X & "," & p.Y & ")") End Sub
End Module Public Class Point
Private yCoord as Integer Private xCoord as Integer Public Property X as Integer Get Return(xCoord * 2) End Get Set(ByVal Value as Integer) xCoord = Value End Set End Property Public Property Y as Integer Get Return(yCoord) End Get Set(ByVal Value as Integer) yCoord = Value End Set End Property
End Class</source>
(0,0) (-200,-100)
Class with a property that performs validation
<source lang="vbnet">Module YourClassTest
Sub Main() Dim obj1 As New YourClass("AAA") Dim obj2 As New YourClass("SSSSSSSSSSSSSSSSSSs") Console.WriteLine(obj1.YourName) Console.WriteLine(obj2.YourName) obj1.YourName = "asdfasdfasdfasdf" Console.WriteLine("obj1"s course name is: " & obj1.YourName) Console.WriteLine("obj2"s course name is: " & obj2.YourName) End Sub " Main
End Module
Public Class YourClass
Private yourNameValue As String " course name for this YourClass Public Sub New(ByVal name As String) YourName = name " validate and store course name End Sub " New Public Property YourName() As String Get " retrieve yourNameValue Return yourNameValue End Get Set(ByVal value As String) If value.Length <= 5 Then " if value has 5 or fewer characters yourNameValue = value " store the course name in the object End If If value.Length > 5 Then " if value has more than 5 characters yourNameValue = value.Substring(0, 5) Console.WriteLine("Name """ & value & """ exceeds maximum length (5).") Console.WriteLine("Limiting name to first 5 characters." & vbCrLf) End If End Set End Property " YourName Public Sub DisplayMessage() Console.WriteLine("Welcome to " & YourName & "!") End Sub " DisplayMessage
End Class</source>
Name "SSSSSSSSSSSSSSSSSSs" exceeds maximum length (5). Limiting name to first 5 characters. AAA SSSSS Name "asdfasdfasdfasdf" exceeds maximum length (5). Limiting name to first 5 characters. obj1"s course name is: asdfa obj2"s course name is: SSSSS
Convert data type in property set
<source lang="vbnet">Public Class YourClass
Private MyState as String = "DEFAULT" Public Property State As String Get Return MyState End Get Set(Value As String) MyState = Value End Set End Property
End Class Module Test
Sub Main() Dim C As New YourClass() Console.WriteLine(C.State) C.State = 5 Console.WriteLine(C.State) End Sub
End Module</source>
DEFAULT 5
Default Property
<source lang="vbnet">Imports System Imports System.Collections Class EmployeeList
Private mEmployees As Hashtable Public Sub New() mEmployees = New Hashtable() End Sub Public Default Property Employee(ByVal ID As Integer) As Employee Get Dim theObject As Object theObject = mEmployees(ID) Return CType(theObject, Employee) End Get Set(ByVal Value As Employee) mEmployees(ID) = Value End Set End Property
End Class Class Employee
Private mName As String Private mWage As Double Private mID As Integer Public Sub New(ByVal name As String, _ ByVal wage As Double, _ ByVal id As Integer) mName = name mWage = wage mID = id End Sub Public Property Name() As String Get Return mName End Get Set(ByVal Value As String) mName = Value End Set End Property Public ReadOnly Property Wage() As Double Get Return mWage End Get End Property Public ReadOnly Property ID() As Integer Get Return mID End Get End Property Public Sub PayRise(ByVal amount As Double) mWage += amount End Sub Public Overrides Function ToString() As String Return "[" & mID & "] " & mName & " " & mWage End Function
End Class
Module Test
Sub Main() Dim employer As New EmployeeList() employer.Employee(1) = New Employee("A", 25000, 1) employer.Employee(2) = New Employee("J", 35000, 2) employer.Employee(3) = New Employee("T", 17000, 3) employer.Employee(4) = New Employee("E", 16500, 4) Dim ID As Integer ID = 2 Dim who As Employee who = employer.Employee(ID) If who Is Nothing Then Console.WriteLine("Unrecognized ID: {0}", ID) Else Console.WriteLine("Employee details: {0}", who) End If End Sub
End Module</source>
Employee details: [2] J 35000
Define and use a Property
<source lang="vbnet">Option Strict On
Imports System Public Class Cat Private mWeight As Integer Public Sub New(ByVal weight As Integer) mWeight = weight End Sub Public Property Weight( ) As Integer Get Return mWeight End Get Set(ByVal Value As Integer) mWeight = Value End Set End Property Public Overrides Function ToString( ) As String Return mWeight.ToString( ) End Function End Class Module Module1 Sub Main( ) Dim theVariable As New Cat(5) Console.WriteLine("In Run. theVariable: {0}",theVariable) Doubler(theVariable) Console.WriteLine("Back in Run. theVariable: {0}",theVariable) End Sub Public Sub Doubler(ByVal param As Cat) Console.WriteLine("In Method1. Received param: {0}",param) param.Weight = param.Weight * 2 Console.WriteLine("Updated param. Returning new value: {0}",param) End Sub End Module</source>
In Run. theVariable: 5 In Method1. Received param: 5 Updated param. Returning new value: 10 Back in Run. theVariable: 10
Do calculation in Property getter
<source lang="vbnet">Imports System Imports System.Data.OleDb Imports System.ruponentModel.ruponent Class Employee
Private MName As String Private MDob As DateTime Private MCompany As String Public Sub New(ByVal name As String, ByVal dob As DateTime) MName = name MDob = dob MCompany = "ABC" End Sub Public Property Name() As String Get Return MName End Get Set(ByVal Value As String) MName = Value End Set End Property Public ReadOnly Property Age() As Integer Get Dim today As DateTime = DateTime.Now Dim Years As Integer = DateTime.Now.Year - mDob.Year If (today.Month < MDob.Month) Or _ (today.Month = MDob.Month And _ today.Day < MDob.Day) Then Years -= 1 End If Return years End Get End Property
End Class Module Test
Sub Main() Dim AEmployee As New Employee("A", New DateTime(1964, 12, 3)) Console.WriteLine("{0} is {1}", AEmployee.Name, AEmployee.Age) End Sub
End Module</source>
A is 42
Do data check in property set
<source lang="vbnet">public class Test
public Shared Sub Main Dim objMyObject As YourClass objMyObject = New YourClass() Console.WriteLine(objMyObject.AddTwoNumbers(1, 2)) objMyObject = Nothing End Sub
End Class Public Class YourClass
Private m_intHeight As Integer Public Property Height() As Integer Get Return m_intHeight End Get Set(ByVal value As Integer) If m_intHeight < 10 Then Exit Property m_intHeight = value End Set End Property Public Function AddTwoNumbers(ByVal intNumber1 As Integer, _ ByVal intNumber2 As Integer) As Long AddTwoNumbers = intNumber1 + intNumber2 End Function
End Class</source>
3
Friend Property
<source lang="vbnet">Imports System Module Test
Sub Main() Dim acct As New Account() Console.WriteLine(acct.AccountHolder) Dim cAcct As New CheckingAccount() Console.WriteLine(cAcct.AccountHolder) End Sub
End Module Public Class CheckingAccount
Inherits Account Sub New() MyBase.New Console.WriteLine(MyBase.retrieved) Console.WriteLine(MyBase.AccountHolder) End Sub
End Class Public Class Account
Protected retrieved As DateTime Private acctHolder As String Public Sub New() retrieved = DateTime.Now() acctHolder = "DEFAULT" End Sub Friend Property AccountHolder As String Get Return acctHolder End Get Set(ByVal Value As String) acctHolder = Value End Set End Property
End Class</source>
DEFAULT 11/05/2007 12:22:44 PM DEFAULT DEFAULT
Loop through two dimensional array with GetUpperBound and GetLowerBound
<source lang="vbnet">Imports System.Collections public class Test
public Shared Sub Main Dim i As Integer Dim j As Integer Dim myArray4(2, 2) As Object "2 dimensional array with 9 elements For i = myArray4.GetLowerBound(0) To myArray4.GetUpperBound(0) For j = myArray4.GetLowerBound(1) To myArray4.GetUpperBound(1) myArray4(i, j) = i + j Next Next For i = myArray4.GetLowerBound(0) To myArray4.GetUpperBound(0) For j = myArray4.GetLowerBound(1) To myArray4.GetUpperBound(1) Console.WriteLine(myArray4(i, j)) Next Next End Sub
End class</source>
0 1 2 1 2 3 2 3 4
MultiKey Properties
<source lang="vbnet">Imports System Imports System.Collections Class Employee
Private MName As String Private MWage As Double Public Sub New(ByVal Name As String, ByVal Wage As Double) MName = Name MWage = Wage End Sub Public Property Name() As String Get Return MName End Get Set(ByVal Value As String) MName = Value End Set End Property Public ReadOnly Property Wage() As Double Get Return MWage End Get End Property Public Sub PayRaise(ByVal Amount As Double) MWage += Amount End Sub Public Overrides Function ToString() As String Return MName & " " & MWage End Function
End Class Class EmployeeList
Private MEmployees As Hashtable Public Sub New() MEmployees = New Hashtable() End Sub Public Property Employee(ByVal Location As String, ByVal ID As Integer) As Employee Get Dim Key As String = Location + ID.ToString() Return MEmployees(Key) End Get Set(ByVal Value As Employee) Dim Key As String = Location + ID.ToString() MEmployees(Key) = Value End Set End Property
End Class Module Test
Sub Main() Dim EmployeeList As New EmployeeList() EmployeeList.Employee("A", 1) = New Employee("S", 2) EmployeeList.Employee("B", 2) = New Employee("C", 3) EmployeeList.Employee("C", 3) = New Employee("B", 1) EmployeeList.Employee("D", 4) = New Employee("A", 1) Dim Who As Employee Who = EmployeeList.Employee("Boston", 200) Console.WriteLine("{0}", Who) Who = EmployeeList.Employee("Geneva", 200) Console.WriteLine("{0}", Who) End Sub
End Module</source>
Overloaded Properties
<source lang="vbnet">Imports System Imports System.Collections Class Employee
Public Name As String Public Wage As Double Public ID As Integer Public Sub New(ByVal N As String, ByVal W As Double, ByVal I As Integer) Name = N Wage = W ID = I End Sub Public Sub PayRaise(ByVal Amount As Double) Wage += Amount End Sub
Public Overrides Function ToString() As String Return "[" & ID & "]" & " " & Name & " " & Wage End Function
End Class Class EmployeeList
Private idTable As Hashtable Private nameTable As Hashtable Public Sub New() idTable = New Hashtable() nameTable = New Hashtable() End Sub Public Property Employee(ByVal ID As Integer) As Employee Get Return idTable(ID) End Get Set(ByVal Value As Employee) idTable(ID) = Value End Set End Property Public Property Employee(ByVal Name As String) As Employee Get Return nameTable(name) End Get Set(ByVal Value As Employee) nameTable(Name) = Value End Set End Property
End Class Module Test
Sub Main() Dim EmployeeList As New EmployeeList() EmployeeList.Employee(1) = New Employee("A", 250, 100) EmployeeList.Employee(2) = New Employee("B", 350, 200) EmployeeList.Employee(3) = New Employee("C", 170, 300) EmployeeList.Employee(4) = New Employee("D", 165, 400) EmployeeList.Employee("N") = New Employee("N", 50000, 500) EmployeeList.Employee("C") = New Employee("C", 60000, 600) Dim ID As Integer = 1 Dim Who As Employee Who = EmployeeList.Employee(ID) If Who Is Nothing Then Console.WriteLine("Unrecognized ID: {0}", ID) Else Console.WriteLine("Employee details: {0}", Who) End If Dim Name As String = "N" Who = EmployeeList.Employee(Name) If Who Is Nothing Then Console.WriteLine("Unrecognized name: {0}", Name) Else Console.WriteLine("Employee details: {0}", Who) End If End Sub
End Module</source>
Employee details: [100] A 250 Employee details: [500] N 50000
Properties with Getter and Setter
<source lang="vbnet">Public Class Tester
Public Shared Sub Main Dim time As New CTime3() " add one second time.Second = (time.Second + 1) Mod 60 " add one minute if 60 seconds have passed If time.Second = 0 Then time.Minute = (time.Minute + 1) Mod 60 " add one hour if 60 minutes have passed If time.Minute = 0 Then time.Hour = (time.Hour + 1) Mod 24 End If End If time.Hour = 1 time.Minute = 2 time.Second = 3 Console.WriteLine("Hour: " & time.Hour & "; Minute: " & _ time.Minute & "; Second: " & time.Second) End Sub
End Class Class CTime3
Inherits Object Private mHour As Integer Private mMinute As Integer Private mSecond As Integer Public Sub New() End Sub " New " property Hour Public Property Hour() As Integer " return mHour value Get Return mHour End Get " set mHour value Set(ByVal value As Integer) If (value >= 0 AndAlso value < 24) Then mHour = value Else mHour = 0 End If End Set End Property " Hour " property Minute Public Property Minute() As Integer " return mMinute value Get Return mMinute End Get " set mMinute value Set(ByVal value As Integer) If (value >= 0 AndAlso value < 60) Then mMinute = value Else mMinute = 0 End If End Set End Property " Minute " property Second Public Property Second() As Integer " return mSecond value Get Return mSecond End Get " set mSecond value Set(ByVal value As Integer) If (value >= 0 AndAlso value < 60) Then mSecond = value Else mSecond = 0 End If End Set End Property " Second
End Class</source>
Hour: 1; Minute: 2; Second: 3
Readable and Writable
<source lang="vbnet">Imports System Class Employee
Private MName As String Private MDob As DateTime Private MEmailAlias As String Public Sub New(ByVal Name As String, ByVal Dob As DateTime) MName = Name MDob = Dob End Sub Public Property Name() As String Get Return MName End Get Set(ByVal Value As String) MName = Value End Set End Property Public ReadOnly Property Brithday() As DateTime Get Return MDob End Get End Property Public WriteOnly Property EmailAlias() As String Set(ByVal Value As String) MEmailAlias = Value End Set End Property Public ReadOnly Property EmailAddress() As String Get Return MEmailAlias & "@a.ru" End Get End Property
End Class Module ReadableAndWritable
Sub Main() Dim emp As New Employee("T", New DateTime(1997, 7, 2)) emp.Name = "T" Console.WriteLine("Name: {0}", emp.Name) Console.WriteLine("Date of birth: {0}", emp.Brithday.ToLongDateString) emp.EmailAlias = "AAA" Console.WriteLine("Email address: {0}", emp.EmailAddress) End Sub
End Module</source>
Name: T Date of birth: July 2, 1997 Email address: AAA@a.ru
ReadOnly property
<source lang="vbnet">Option Strict On Public Class YourClass
Private yourName As String Private yourNumber As Decimal Public Sub New(breed As String) yourName = breed End Sub Public ReadOnly Property Name() As String Get Return yourName End Get End Property Public Property Number() As Decimal Get Return yourNumber End Get Set yourNumber = CDec(value) End Set End Property Public Sub ShowInfo() Console.WriteLine("This " & yourName & " weighs " & yourNumber & " pounds.") End Sub
End Class Public Class Tester
Public Shared Sub Main() Dim mal As New YourClass("A") mal.Number = 130 ChangeYourClassInfo(mal) mal.ShowInfo CompletelyChangeYourClassInfo(mal) mal.ShowInfo End Sub Public Shared Sub ChangeYourClassInfo(ByVal aYourClass As YourClass) aYourClass.Number = 125 End Sub Public Shared Sub CompletelyChangeYourClassInfo(ByVal aYourClass As YourClass) Dim newf As New YourClass("Newfoundland") aYourClass = newf End Sub
End Class</source>
This A weighs 125 pounds. This A weighs 125 pounds.
<source lang="vbnet">Imports System Class Person
Private Shared MDomain As String Private Name As String Private Birthday As DateTime Private EmailAlias As String Public Shared Property Domain() As String Get Return MDomain End Get Set(ByVal Value As String) MDomain = Value End Set End Property Public Sub New(ByVal N As String, ByVal Dob As DateTime) Name = N Birthday = Dob End Sub
End Class Module Test
Sub Main() Dim APerson As New Person("P", New DateTime(1997, 7, 2)) Person.Domain = "My.ru" End Sub
End Module</source>
<source lang="vbnet">Module Tester
Sub Main() Console.WriteLine("Employees before instantiation: " & _ Employee.Count) Dim employee1 As Employee = New Employee("S", "B") Dim employee2 As Employee = New Employee("B", "J") Console.WriteLine("Employee.Count: " & Employee.Count) employee1 = Nothing employee2 = Nothing System.GC.Collect() " request garbage collection Console.WriteLine("Employee.Count: " & Employee.Count) End Sub " Main
End Module Class Employee
Inherits Object Private mFirstName As String Private mLastName As String Private Shared mCount As Integer Public Sub New(ByVal firstNameValue As String, _ ByVal lastNameValue As String) mFirstName = firstNameValue mLastName = lastNameValue mCount += 1 Console.WriteLine _ ("Employee object constructor: " & mFirstName & _ " " & mLastName) End Sub " New Protected Overrides Sub Finalize() mCount -= 1 " decrement mCount, resulting in one fewer object Console.WriteLine _ ("Employee object finalizer: " & mFirstName & _ " " & mLastName & "; count = " & mCount) End Sub " Finalize Public ReadOnly Property FirstName() As String Get Return mFirstName End Get End Property " FirstName " return last name Public ReadOnly Property LastName() As String Get Return mLastName End Get End Property " LastName " property Count Public Shared ReadOnly Property Count() As Integer Get Return mCount End Get End Property " Count
End Class</source>
Employees before instantiation: 0 Employee object constructor: S B Employee object constructor: B J Employee.Count: 2 Employee object finalizer: B J; count = 1 Employee object finalizer: S B; count = 0 Employee.Count: 0
Single Indexed Property
<source lang="vbnet">Imports System Imports System.Collections Class Employee
Public Name As String Public Wage As Double Public Sub New(ByVal N As String, ByVal W As Double) Name = N Wage = W End Sub Public Sub PayRaise(ByVal Amount As Double) Wage += Amount End Sub Public Overrides Function ToString() As String Return Name & " " & Wage End Function
End Class Class Employer
Private MEmployees As Hashtable Public Sub New() MEmployees = New Hashtable() End Sub Public Property Employee(ByVal ID As Integer) As Employee Get Dim TheObject As Object TheObject = MEmployees.Item(ID) Return CType(TheObject, Employee) End Get Set(ByVal Value As Employee) MEmployees.Item(ID) = Value End Set End Property
End Class Module Test
Sub Main() Dim Employer As New Employer() Employer.Employee(1) = New Employee("A", 25000) Employer.Employee(2) = New Employee("J", 35000) Employer.Employee(3) = New Employee("T", 17000) Employer.Employee(4) = New Employee("E", 16500) Dim ID As Integer = 3 Dim Who As Employee Who = employer.Employee(ID) If Who Is Nothing Then Console.WriteLine("Unrecognized ID: {0}", ID) Else Console.WriteLine("Employee details: {0}", Who) End If End Sub
End Module</source>
Employee details: T 17000
Throw Exception in Property setting
<source lang="vbnet">Imports System Module Test
Sub Main() Dim p as Point = New Point() Console.WriteLine("(" & p.X & "," & p.Y & ")") Try p.X = -100 p.Y = -100 Catch e as ArgumentOutOfRangeException Console.WriteLine(e.Message) End Try Console.WriteLine("(" & p.X & "," & p.Y & ")") End Sub
End Module Public Class Point
Private yCoord as Integer Private xCoord as Integer Public Property X as Integer Get Return xCoord End Get Set(ByVal Value as Integer) If Value < 0 then Throw New ArgumentOutOfRangeException("Value","X Coordinate must be greater than 0") End If xCoord = Value End Set End Property Public Property Y as Integer Get Return(yCoord) End Get Set(ByVal Value as Integer) If Value < 0 then Throw new ArgumentOutOfRangeException("Value","Y Coordinate must be greater than 0") End If yCoord = Value End Set End Property
End Class</source>
(0,0) X Coordinate must be greater than 0 Parameter name: Value (0,0)
Two properties
<source lang="vbnet">Imports System Imports System.Collections Class EmployeeList
Private mEmployees As Hashtable Private mLevels As Hashtable Public Sub New() mEmployees = New Hashtable() mLevels = New Hashtable() End Sub Public Default Property Employee(ByVal ID As Integer) As Employee Get Dim theObject As Object theObject = mEmployees(ID) Return CType(theObject, Employee) End Get Set(ByVal Value As Employee) mEmployees(ID) = Value End Set End Property Public Property Level(ByVal country As String) As String Get Dim theObject As Object theObject = mLevels(country) Return CType(theObject, String) End Get Set(ByVal Value As String) mLevels(country) = Value End Set End Property
End Class
Class Employee
Private mName As String Private mWage As Double Private mID As Integer Public Sub New(ByVal name As String, ByVal wage As Double,ByVal id As Integer) mName = name mWage = wage mID = id End Sub Public Property Name() As String Get Return mName End Get Set(ByVal Value As String) mName = Value End Set End Property Public ReadOnly Property Wage() As Double Get Return mWage End Get End Property Public ReadOnly Property ID() As Integer Get Return mID End Get End Property Public Sub PayRise(ByVal amount As Double) mWage += amount End Sub Public Overrides Function ToString() As String Return "[" & mID & "] " & mName & " " & mWage End Function
End Class Module DefaultProperty
Sub Main() Dim employer As New EmployeeList() employer(1) = New Employee("A", 25, 1) employer(2) = New Employee("J", 35, 2) employer(3) = New Employee("T", 17, 3) employer(4) = New Employee("E", 16, 4) employer.Level("AA") = "A" employer.Level("BB") = "B" employer.Level("CC") = "C" employer.Level("DD") = "D" employer.Level("EE") = "E" employer.Level("FF") = "F" Dim country As String country = "AA" Dim city As String city = employer.Level(country) If city Is Nothing Then Console.WriteLine("No office in {0}", country) Else Console.WriteLine("Level in {0}: {1}", country, city) End If End Sub
End Module</source>
Level in AA: A
Use Property to set private data
<source lang="vbnet">Module Module1
Sub Main() Dim TheObject As New TheClass Console.WriteLine("ThePublicData holds """ & TheObject.ThePublicData & """") Console.WriteLine("TheMethod returns """ & TheObject.TheMethod() & """") Console.WriteLine("TheProperty holds """ & TheObject.TheProperty & """") End Sub
End Module Class TheClass
Public ThePublicData = "Hello there!" Private TheInternalData As String = "Hello there!" Function TheMethod() As String Return "Hello there!" End Function Public Property TheProperty() As String Get Return TheInternalData End Get Set(ByVal Value As String) TheInternalData = Value End Set End Property
End Class</source>
ThePublicData holds "Hello there! TheMethod returns "Hello there! TheProperty holds "Hello there!