VB.Net/Language Basics/Function Parameter
Версия от 16:40, 26 мая 2010; (обсуждение)
Содержание
Calculates the power of a value, defaults to square
Imports System
Public Class MainClass
Shared Sub Main(ByVal args As String())
Dim value As Integer
" call version of Power depending on power input
value = Power(Convert.ToInt32(3), _
Convert.ToInt32(10))
Console.WriteLine( Convert.ToString(value) )
End Sub
" use iteration to calculate power
Shared Function Power(ByVal base As Integer, _
Optional ByVal exponent As Integer = 2) As Integer
Dim total As Integer = 1
Dim i As Integer
For i = 1 To exponent
total *= base
Next
Return total
End Function " Power
End Class
Pass Array as Parameters
Imports System
Public Class MainClass
Shared Sub Main(ByVal args As String())
Dim friends() As String = {"A", "B", "C","D", "E"}
AddFriendsToList(friends)
End Sub
Shared Sub AddFriendsToList(ByVal friends() As String)
Dim friendName As String
For Each friendName In friends
Console.WriteLine("[" & friendName & "]")
Next
End Sub
End Class
Two Dimension Array: Pass into a Function
Imports System
Public Class MainClass
Shared Sub Main(ByVal args As String())
" define an array to hold friends in...
Dim friends(2, 2) As String
" set the data...
friends(0, PersonDataIndex.Name) = "Name 1"
friends(0, PersonDataIndex.Email) = "Email 1"
friends(0, PersonDataIndex.Sex) = "Sex 1"
friends(1, PersonDataIndex.Name) = "Name 2"
friends(1, PersonDataIndex.Email) = "Email 2"
friends(1, PersonDataIndex.Sex) = "Ses 2"
friends(2, PersonDataIndex.Name) = "Name 3"
friends(2, PersonDataIndex.Email) = "Email 3"
friends(2, PersonDataIndex.Sex) = "Sex 3"
AddFriendsToList(friends)
End Sub
Shared Sub AddFriendsToList(ByVal friends(,) As String)
Dim row As Integer
For row = 0 To UBound(friends, 1)
Dim buf As String = ""
Dim column As Integer
For column = 0 To UBound(friends, 2)
buf &= friends(row, column) & ", "
Next
Console.WriteLine(buf)
Next
End Sub
End Class
Public Enum PersonDataIndex As Integer
Name = 0
Email = 1
Sex = 2
End Enum
Use Array as Function Parameter
Imports System
Public Class MainClass
Shared Sub Main(ByVal args As String())
Dim a As Integer = 5
Dim b As Integer = 6
Dim c As Integer = 7
Console.WriteLine("Calling with three Integers")
DisplayVals(a, b, c)
Console.WriteLine("Calling with four Integers")
DisplayVals(5, 6, 7, 8)
Console.WriteLine("calling with an array of four Integers")
Dim explicitArray( ) As Integer = {5, 6, 7, 8}
DisplayVals(explicitArray)
End Sub
Shared Public Sub DisplayVals(ByVal ParamArray intVals( ) As Integer)
Dim i As Integer
For Each i In intVals
Console.WriteLine("DisplayVals {0}", i)
Next i
End Sub "DisplayVals
End Class