VB.Net Tutorial/Class Module/Method
Версия от 16:40, 26 мая 2010; (обсуждение)
Define member methods
Module Tester
Sub Main()
Dim circle As CCircle
circle = New CCircle(37, 43, 2.5) " instantiate CCircle
Console.WriteLine("X coordinate is " & circle.X & vbCrLf & _
"Y coordinate is " & circle.Y & vbCrLf & "Radius is " & _
circle.Radius)
circle.X = 2
circle.Y = 2
circle.Radius = 4.25
Console.WriteLine("The new location and radius of circle are " & _
vbCrLf & circle.ToString())
Console.WriteLine("Diameter is " & _
String.Format("{0:F}", circle.Diameter()))
Console.WriteLine("Circumference is " & _
String.Format("{0:F}", circle.Circumference()))
Console.WriteLine(String.Format("{0:F}", circle.Area()))
End Sub " Main
End Module
Public Class CCircle
Private mX, mY As Integer
Private mRadius As Double " CCircle"s radius
Public Sub New()
X = 0
Y = 0
Radius = 0
End Sub " New
Public Sub New(ByVal xValue As Integer, _
ByVal yValue As Integer, ByVal radiusValue As Double)
X = xValue
Y = yValue
Radius = radiusValue
End Sub " New
Public Property X() As Integer
Get
Return mX
End Get
Set(ByVal xValue As Integer)
mX = xValue " no need for validation
End Set
End Property " X
Public Property Y() As Integer
Get
Return mY
End Get
Set(ByVal yValue As Integer)
mY = yValue " no need for validation
End Set
End Property " Y
Public Property Radius() As Double
Get
Return mRadius
End Get
Set(ByVal radiusValue As Double)
If radiusValue > 0 Then
mRadius = radiusValue
End If
End Set
End Property " Radius
Public Function Diameter() As Double
Return mRadius * 2
End Function " Diameter
Public Function Circumference() As Double
Return Math.PI * Diameter()
End Function " Circumference
Public Function Area() As Double
Return Math.PI * mRadius ^ 2
End Function " Area
Public Overrides Function ToString() As String
Return "Center = " & "[" & mX & ", " & mY & "]" & _
"; Radius = " & mRadius
End Function
End Class
X coordinate is 37 Y coordinate is 43 Radius is 2.5 The new location and radius of circle are Center = [2, 2]; Radius = 4.25 Diameter is 8.50 Circumference is 26.70 56.75
Method with parameter
Option Strict On
Imports System
Public Class TestClass
Sub SomeMethod(ByVal firstParam As Integer, ByVal secondParam As Single)
Console.WriteLine("received: {0}, {1}",firstParam, secondParam)
End Sub
End Class
Module Module1
Sub Main( )
Dim howManyPeople As Integer = 5
Dim pi As Single = 3.14F
Dim tc As New TestClass( )
tc.SomeMethod(howManyPeople, pi)
End Sub
End Module
received: 5, 3.14