Instrução Function (Visual Basic)
Declares the name, parameters, and code that define a Function procedure.
Observação |
---|
Visual Basic 2008apresenta as expressões lambda, que permitem que você definir expressões de função na linha. For more information, see Expressão de função (Visual Basic) and Expressões Lambda (Visual Basic). |
[ <attributelist> ] [ accessmodifier ] [ proceduremodifiers ] [ Shared ] [ Shadows ]
Function name [ (Of typeparamlist) ] [ (parameterlist) ] [ As returntype ] [ Implements implementslist | Handles eventlist ]
[ statements ]
[ Exit Function ]
[ statements ]
End Function
Parts
Term |
Definition |
attributelist |
Optional. See Attribute List. |
accessmodifier |
Optional. Can be one of the following: |
proceduremodifiers |
Optional. Can be one of the following:
|
Shared |
Optional. See Shared. |
Shadows |
Optional. See Shadows. |
name |
Required. Name of the procedure. See Nomes de elementos declarados (Visual Basic). |
typeparamlist |
Optional. List of type parameters for a generic procedure. See Type List. |
parameterlist |
Optional. List of local variable names representing the parameters of this procedure. See Lista de parâmetros (Visual Basic). |
returntype |
Required if Option Strict is On. Data type of the value returned by this procedure. |
Implements |
Optional. Indicates that this procedure implements one or more Function procedures, each one defined in an interface implemented by this procedure's containing class or structure. See Implementa Declaração. |
implementslist |
Required if Implements is supplied. List of Function procedures being implemented. implementedprocedure [ , implementedprocedure ... ] Each implementedprocedure has the following syntax and parts: interface.definedname
PartDescription
interface Required.Name of an interface implemented by this procedure's containing class or structure.
definedname Required.Name by which the procedure is defined in interface.
|
Handles |
Optional. Indicates that this procedure can handle one or more specific events. See Cláusula Handles (Visual Basic). |
eventlist |
Required if Handles is supplied. List of events this procedure handles. eventspecifier [ , eventspecifier ... ] Each eventspecifier has the following syntax and parts: eventvariable.event
PartDescription
eventvariable Required.Object variable declared with the data type of the class or structure that raises the event.
event Required.Name of the event this procedure handles.
|
statements |
Optional. Block of statements to be executed within this procedure. |
End Function |
Terminates the definition of this procedure. |
Comentários
All executable code must be inside a procedure. Each procedure in turn is declared within a class, structure, or module, which is called the containing class, structure, or module.
Use a Function procedure when you need to return a value to the calling code. Use a Sub procedure when you do not need to return a value.
Você pode definir um Function procedimento somente no nível de módulo . This means the declaration context for a function must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Contextos de declaração e níveis de acesso padrão (Visual Basic).
Function procedures default to public access. You can adjust their access levels with the access modifiers.
Você pode chamar um Function procedimento no lado direito de uma expressão quando desejar usar o valor retornado pela função. You use the Function procedure the same way you use any library function such as Sqrt, Cos, or ChrW.
You call a Function procedure by using the procedure name, followed by the argument list in parentheses, in an expression. You can omit the parentheses only if you are not supplying any arguments. However, your code is more readable if you always include the parentheses.
A function can also be called using the Call statement, in which case the return value is ignored.
Rules
Return Type. O Functiondedemonstrativo pode declarar o tipo de dados de que o valor retornado. You can specify any data type or the name of an enumeration, structure, class, or interface.
If you do not specify returntype, the procedure returns Object.
Implementação. Se este procedimento usa o Implementspalavra-chave, o que contém uma classe ou estrutura também deve ter um Implementsademonstrativo imediatamente seguinte sua Class ou Structuredemonstrativo. The Implements statement must include each interface specified in implementslist. However, the name by which an interface defines the Function (in definedname) does not have to be the same as the name of this procedure (in name).
Behavior
Returning from a Procedure. Quando o Function procedimento retorna para o código de chamada, a execução continua com a demonstrativo após a demonstrativo que chamou.
The Exit Function and Return statements cause an immediate exit from a Function procedure. Any number of Exit Function and Return statements can appear anywhere in the procedure, and you can mix Exit Function and Return statements.
Valorde retorno. Para retornar um valor de uma função, você pode atribuir o valor ao nome da função ou incluí-lo em um Return demonstrativo. The following example assigns the return value to the function name myFunction and then uses the Exit Function statement to return.
Function myFunction(ByVal j As Integer) As Double myFunction = 3.87 * j Exit Function End Function
If you use Exit Function without assigning a value to name, the procedure returns the default value for the data type specified in returntype. If returntype is not specified, the procedure returns Nothing, the default value for Object.
The Return statement simultaneously assigns the return value and exits the function. The following example shows this.
Function myFunction(ByVal j As Integer) As Double Return 3.87 * j End Function
Troubleshooting
- Order of Execution. Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason, avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.
Exemplo
The following example uses the Function statement to declare the name, parameters, and code that form the body of a Function procedure. The ParamArray modifier enables the function to accept a variable number of arguments.
Public Function calcSum(ByVal ParamArray args() As Double) As Double
calcSum = 0
If args.Length <= 0 Then Exit Function
For i As Integer = 0 To UBound(args, 1)
calcSum += args(i)
Next i
End Function
The following example invokes the function declared in the preceding example.
Module Module1
Sub Main()
' In the following function call, calcSum's local variables
' are assigned the following values: args(0) = 4, args(1) = 3,
' and so on. The displayed sum is 10.
Dim returnedValue As Double = calcSum(4, 3, 2, 1)
Console.WriteLine("Sum: " & returnedValue)
' Parameter args accepts zero or more arguments. The sum
' displayed by the following statements is 0.
returnedValue = calcSum()
Console.WriteLine("Sum: " & returnedValue)
End Sub
Public Function calcSum(ByVal ParamArray args() As Double) As Double
calcSum = 0
If args.Length <= 0 Then Exit Function
For i As Integer = 0 To UBound(args, 1)
calcSum += args(i)
Next i
End Function
End Module
Consulte também
Tarefas
Como: Usar uma classe genérica (Visual Basic)
Solucionando problemas de procedimentos (Visual Basic)
Referência
Lista de parâmetros (Visual Basic)
Expressão de função (Visual Basic)