Function 陳述式 (Visual Basic)Function Statement (Visual Basic)

宣告定義 Function 程式的名稱、參數和程式碼。Declares the name, parameters, and code that define a Function procedure.

語法Syntax

[ <attributelist> ] [ accessmodifier ] [ proceduremodifiers ] [ Shared ] [ Shadows ] [ Async | Iterator ]
Function name [ (Of typeparamlist) ] [ (parameterlist) ] [ As returntype ] [ Implements implementslist | Handles eventlist ]
    [ statements ]
    [ Exit Function ]
    [ statements ]
End Function

組件Parts

  • attributelist

    選擇項。Optional. 請參閱屬性清單See Attribute List.

  • accessmodifier

    選擇項。Optional. 可以是下列其中一項:Can be one of the following:

    請參閱 Access levels in Visual BasicSee Access levels in Visual Basic.

  • proceduremodifiers

    選擇項。Optional. 可以是下列其中一項:Can be one of the following:

  • Shared

    選擇項。Optional. 請參閱共用See Shared.

  • Shadows

    選擇項。Optional. 請參閱ShadowsSee Shadows.

  • Async

    選擇項。Optional. 請參閱AsyncSee Async.

  • Iterator

    選擇項。Optional. 請參閱IteratorSee Iterator.

  • name

    必要項。Required. 程式的名稱。Name of the procedure. 請參閱 Declared Element NamesSee Declared Element Names.

  • 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 Parameter List.

  • returntype

    如果 Option Strict On,則為必要。Required if Option Strict is On. 這個程式所傳回之值的資料類型。Data type of the value returned by this procedure.

  • Implements

    選擇項。Optional. 指出此程式會執行一或多個 Function 程式,其中每一個都是在由這個程式的包含類別或結構所實的介面中定義。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. 請參閱Implements 語句See Implements Statement.

  • implementslist

    如果使用 Implements,則為必要項。Required if Implements is supplied. 實作之 Function 程序的清單。List of Function procedures being implemented.

    implementedprocedure [ , implementedprocedure ... ]

    每個 implementedprocedure 都具有下列語法和組件:Each implementedprocedure has the following syntax and parts:

    interface.definedname

    組件Part 描述Description
    interface 必要項。Required. 此程式的包含類別或結構所實作為介面的名稱。Name of an interface implemented by this procedure's containing class or structure.
    definedname 必要項。Required. 名稱,據以在 interface 中定義程序。Name by which the procedure is defined in interface.
  • Handles

    選擇項。Optional. 指出此程式可以處理一或多個特定事件。Indicates that this procedure can handle one or more specific events. 請參閱控制碼See Handles.

  • eventlist

    如果使用 Handles,則為必要項。Required if Handles is supplied. 此程式處理的事件清單。List of events this procedure handles.

    eventspecifier [ , eventspecifier ... ]

    每個 eventspecifier 都具有下列語法和組件:Each eventspecifier has the following syntax and parts:

    eventvariable.event

    組件Part 描述Description
    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.

備註Remarks

所有可執行檔程式碼都必須在程式內。All executable code must be inside a procedure. 接著,每個程式都會在類別、結構或稱為包含類別、結構或模組的模組中宣告。Each procedure, in turn, is declared within a class, a structure, or a module that is referred to as the containing class, structure, or module.

若要將值傳回給呼叫程式碼,請使用 Function 程式。否則,請使用 Sub 程式。To return a value to the calling code, use a Function procedure; otherwise, use a Sub procedure.

定義函數Defining a Function

您只能在模組層級定義 Function 程式。You can define a Function procedure only at the module level. 因此,函式的宣告內容必須是類別、結構、模組或介面,而且不能是原始程式檔、命名空間、程式或區塊。Therefore, the declaration context for a function must be a class, a structure, a module, or an interface and can't be a source file, a namespace, a procedure, or a block. 如需詳細資訊,請參閱宣告內容和預設存取層級For more information, see Declaration Contexts and Default Access Levels.

Function 程式預設為公開存取。Function procedures default to public access. 您可以使用存取修飾詞來調整其存取層級。You can adjust their access levels with the access modifiers.

@No__t_0 程式可以宣告此程式所傳回值的資料類型。A Function procedure can declare the data type of the value that the procedure returns. 您可以指定任何資料類型或列舉的名稱、結構、類別或介面。You can specify any data type or the name of an enumeration, a structure, a class, or an interface. 如果您未指定 returntype 參數,程式會傳回 ObjectIf you don't specify the returntype parameter, the procedure returns Object.

如果此程式使用 Implements 關鍵字,則包含的類別或結構也必須有緊接在其 ClassStructure 語句後面的 Implements 語句。If this procedure uses the Implements keyword, the containing class or structure must also have an Implements statement that immediately follows its Class or Structure statement. @No__t_0 語句必須包含 implementslist 中指定的每個介面。The Implements statement must include each interface that's specified in implementslist. 不過,介面用來定義 Function (在 definedname 中)的名稱不需要符合此程式的名稱(在 name 中)。However, the name by which an interface defines the Function (in definedname) doesn't need to match the name of this procedure (in name).

注意

您可以使用 lambda 運算式來定義內嵌函數運算式。You can use lambda expressions to define function expressions inline. 如需詳細資訊,請參閱函數運算式Lambda 運算式For more information, see Function Expression and Lambda Expressions.

從函式傳回Returning from a Function

Function 程式回到呼叫程式碼時,執行會繼續進行呼叫程式之語句後面的語句。When the Function procedure returns to the calling code, execution continues with the statement that follows the statement that called the procedure.

若要從函式傳回值,您可以將值指派給函數名稱,或將它包含在 Return 語句中。To return a value from a function, you can either assign the value to the function name or include it in a Return statement.

@No__t_0 語句會同時指派傳回值並結束函式,如下列範例所示。The Return statement simultaneously assigns the return value and exits the function, as the following example shows.

Function MyFunction(ByVal j As Integer) As Double
    Return 3.87 * j
End Function

下列範例會將傳回值指派給函數名稱 myFunction,然後使用 Exit Function 語句傳回。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

@No__t_0 和 Return 語句會導致立即離開 Function 程式。The Exit Function and Return statements cause an immediate exit from a Function procedure. 任何數目的 Exit FunctionReturn 語句都可以出現在程式中的任何位置,而且您可以混合 Exit FunctionReturn 語句。Any number of Exit Function and Return statements can appear anywhere in the procedure, and you can mix Exit Function and Return statements.

如果您使用 Exit Function,但未指派值給 name,則程式會傳回 returntype 中指定之資料類型的預設值。If you use Exit Function without assigning a value to name, the procedure returns the default value for the data type that's specified in returntype. 如果未指定 returntype,程式會傳回 Nothing,這是 Object 的預設值。If returntype isn't specified, the procedure returns Nothing, which is the default value for Object.

呼叫函式Calling a Function

您可以在運算式中使用程式名稱,後面接著以括弧括住的引數清單,來呼叫 Function 程式。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 aren't supplying any arguments. 不過,如果您一律包含括弧,則程式碼會更容易閱讀。However, your code is more readable if you always include the parentheses.

呼叫 Function 程式的方式,與呼叫任何程式庫函式(例如 SqrtCosChrW)相同。You call a Function procedure the same way that you call any library function such as Sqrt, Cos, or ChrW.

您也可以使用 Call 關鍵字來呼叫函數。You can also call a function by using the Call keyword. 在此情況下,會忽略傳回值。In that case, the return value is ignored. 在大部分的情況下,不建議使用 Call 關鍵字。Use of the Call keyword isn't recommended in most cases. 如需詳細資訊,請參閱Call 語句For more information, see Call Statement.

Visual Basic 有時會重新排列算術運算式,以提高內部效率。Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. 基於這個理由,當函數變更同一個運算式中的變數值時,您不應該在算術運算式中使用 Function 程式。For that reason, you shouldn't use a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.

Async 函式Async Functions

非同步功能可讓您在不使用明確回呼的情況下叫用非同步函式,或在多個函式或 lambda 運算式中手動分割程式碼。The Async feature allows you to invoke asynchronous functions without using explicit callbacks or manually splitting your code across multiple functions or lambda expressions.

如果您使用Async修飾詞來標示函式,您可以在函式中使用Await運算子。If you mark a function with the Async modifier, you can use the Await operator in the function. 當控制項到達 Async 函式中的 Await 運算式時,控制項會回到呼叫端,而函式中的進度會暫停,直到等候的工作完成為止。When control reaches an Await expression in the Async function, control returns to the caller, and progress in the function is suspended until the awaited task completes. 當工作完成時,可以在函式中繼續執行。When the task is complete, execution can resume in the function.

注意

@No__t_0 程式會在遇到第一個尚未完成的等候物件,或到達 Async 程式結尾(以先發生者為准)時,將它傳回給呼叫端。An Async procedure returns to the caller when either it encounters the first awaited object that’s not yet complete, or it gets to the end of the Async procedure, whichever occurs first.

@No__t_0 函式的傳回型別可以是 Task<TResult>TaskAn Async function can have a return type of Task<TResult> or Task. 以下提供具有 Task<TResult> 傳回類型之 Async 函式的範例。An example of an Async function that has a return type of Task<TResult> is provided below.

@No__t_0 函數不能宣告任何ByRef參數。An Async function cannot declare any ByRef parameters.

Sub 語句也可以使用 Async 修飾詞來標記。A Sub Statement can also be marked with the Async modifier. 這主要用於事件處理常式,無法傳回值。This is primarily used for event handlers, where a value cannot be returned. 無法等候 Async Sub 程式,而且 Async Sub 程式的呼叫端無法攔截 Sub 程式擲回的例外狀況。An Async Sub procedure can't be awaited, and the caller of an Async Sub procedure can't catch exceptions that are thrown by the Sub procedure.

如需 Async 函式的詳細資訊,請參閱使用 async 和 Await 進行非同步程式設計非同步程式中的控制流程非同步傳回類型For more information about Async functions, see Asynchronous Programming with Async and Await, Control Flow in Async Programs, and Async Return Types.

Iterator 函式Iterator Functions

Iterator函式會對集合執行自訂反復專案,例如清單或陣列。An iterator function performs a custom iteration over a collection, such as a list or array. Iterator 函數會使用Yield語句,一次傳回一個元素。An iterator function uses the Yield statement to return each element one at a time. 當達到Yield語句時,會記住程式碼中的目前位置。When a Yield statement is reached, the current location in code is remembered. 下次呼叫迭代器函式時,便會從這個位置重新開始執行。Execution is restarted from that location the next time the iterator function is called.

您可以從用戶端程式代碼呼叫反覆運算器,方法是使用For Each 。下一個語句。You call an iterator from client code by using a For Each…Next statement.

Iterator 函數的傳回類型可以是 IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>The return type of an iterator function can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.

如需詳細資訊,請參閱迭代器For more information, see Iterators.

範例Example

下列範例會使用 Function 語句,宣告構成 Function 程式主體的名稱、參數和程式碼。The following example uses the Function statement to declare the name, parameters, and code that form the body of a Function procedure. @No__t_0 修飾詞可讓函式接受可變數目的引數。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

範例Example

下列範例會叫用上述範例中所宣告的函式。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

範例Example

在下列範例中,DelayAsync 是具有 Task<TResult> 傳回類型的 Async FunctionIn the following example, DelayAsync is an Async Function that has a return type of Task<TResult>. DelayAsync 具有傳回整數的 Return 陳述式。DelayAsync has a Return statement that returns an integer. 因此,DelayAsync 的函式宣告必須具有 Task(Of Integer) 的傳回類型。Therefore the function declaration of DelayAsync needs to have a return type of Task(Of Integer). 因為傳回型別是 Task(Of Integer),所以 DoSomethingAsyncAwait 運算式的評估會產生整數。Because the return type is Task(Of Integer), the evaluation of the Await expression in DoSomethingAsync produces an integer. 這會在此語句中示範: Dim result As Integer = Await delayTaskThis is demonstrated in this statement: Dim result As Integer = Await delayTask.

@No__t_0 的程式是 Async Sub 程式的範例。The startButton_Click procedure is an example of an Async Sub procedure. 因為 DoSomethingAsyncAsync 函式,所以必須等候 DoSomethingAsync 呼叫的工作,如下列語句所示: Await DoSomethingAsync()Because DoSomethingAsync is an Async function, the task for the call to DoSomethingAsync must be awaited, as the following statement demonstrates: Await DoSomethingAsync(). @No__t_0 Sub 程式必須使用 Async 修飾詞加以定義,因為它有 Await 運算式。The startButton_Click Sub procedure must be defined with the Async modifier because it has an Await expression.

' Imports System.Diagnostics
' Imports System.Threading.Tasks

' This Click event is marked with the Async modifier.
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs) Handles startButton.Click
    Await DoSomethingAsync()
End Sub

Private Async Function DoSomethingAsync() As Task
    Dim delayTask As Task(Of Integer) = DelayAsync()
    Dim result As Integer = Await delayTask

    ' The previous two statements may be combined into
    ' the following statement.
    ' Dim result As Integer = Await DelayAsync()

    Debug.WriteLine("Result: " & result)
End Function

Private Async Function DelayAsync() As Task(Of Integer)
    Await Task.Delay(100)
    Return 5
End Function

'  Output:
'   Result: 5

請參閱See also