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

宣告定義程式的名稱、參數和程式碼 FunctionDeclares 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:

    請參閱Visual Basic 中的存取層級See 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 為,則為必要 OnRequired 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 ; 否則,請使用程式 SubTo 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.

程式可以宣告此程式所傳回 Function 值的資料類型。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 關鍵字,則包含的類別或結構也必須有 Implements 緊接在其或語句後面的語句 Class StructureIf 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. Implements語句必須包含中所指定的每個介面 implementslistThe 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.

Return語句會同時指派傳回值並結束函式,如下列範例所示。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 FunctionThe 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

Exit FunctionReturn 語句會導致程式立即結束 FunctionThe 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 ,則程式會傳回中所指定之資料類型的預設值 returntypeIf 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 程式會傳回,這是的預設值 ObjectIf 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 程式的方法與呼叫任何程式庫函式(例如、或)的方式相同 Sqrt Cos ChrWYou call a Function procedure the same way that you call any library function such as Sqrt, Cos, or ChrW.

您也可以使用關鍵字來呼叫函式 CallYou 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. 當控制項到達函式 Await 中的運算式時 Async ,控制項會回到呼叫端,而函式中的進度會暫停,直到等候的工作完成為止。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.

注意

程式會 Async 在遇到第一個尚未完成的等候物件,或到達程式結尾 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.

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

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

Sub 語句也可以使用修飾詞來標記 AsyncA 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 無法攔截程式所擲回的例外狀況 SubAn 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 會使用語句來宣告構成程式主體的名稱、參數和代碼 FunctionThe following example uses the Function statement to declare the name, parameters, and code that form the body of a Function procedure. ParamArray修飾詞可讓函式接受可變數目的引數。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

在下列範例中, DelayAsyncAsync Function 具有傳回類型的 Task<TResult>In 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) ,所以 Await 中的運算式評估會 DoSomethingAsync 產生整數。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.

此程式 startButton_Click 是程式的範例 Async SubThe startButton_Click procedure is an example of an Async Sub procedure. 因為 DoSomethingAsync 是函式 Async ,所以的呼叫工作必須等候 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(). 程式 startButton_Click 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