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 Basic」を参照してください。See Access levels in Visual Basic.
proceduremodifiers
任意。Optional. 次のいずれかの値を指定します。Can be one of the following:
MustOverride Overrides
NotOverridable Overrides
Shared
Shadows
Async
Iterator
name
必須です。Required. プロシージャの名前。Name of the procedure. 「 Declared Element Names」を参照してください。See 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 ifOption Strict
isOn
. このプロシージャによって返される値のデータ型。Data type of the value returned by this procedure.Implements
任意。Optional. それぞれこのプロシージャの含まれているクラスまたは構造体によって実装されたインターフェイスに定義されている、1 つ以上の
Function
プロシージャを、このプロシージャが実装することを示します。Indicates that this procedure implements one or moreFunction
procedures, each one defined in an interface implemented by this procedure's containing class or structure. 「Implements ステートメント」を参照してください。See Implements Statement.implementslist
Implements
を指定する場合は、必ず指定します。Required ifImplements
is supplied. 実装されるFunction
プロシージャのリストです。List ofFunction
procedures being implemented.implementedprocedure [ , implementedprocedure ... ]
implementedprocedure
の構文と指定項目は次のとおりです。Eachimplementedprocedure
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 ininterface
.Handles
任意。Optional. このプロシージャで 1 つ以上の特定のイベントを処理できることを示します。Indicates that this procedure can handle one or more specific events. 「Handles」を参照してください。See Handles.
eventlist
Handles
を指定する場合は、必ず指定します。Required ifHandles
is supplied. このプロシージャで処理するイベントの一覧。List of events this procedure handles.eventspecifier [ , eventspecifier ... ]
eventspecifier
の構文と指定項目は次のとおりです。Eacheventspecifier
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.
RemarksRemarks
すべての実行可能コードは、プロシージャ内になければなりません。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.
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
パラメーターを指定しない場合、プロシージャから Object
が返されます。If you don't specify the returntype
parameter, the procedure returns Object
.
このプロシージャで Implements
キーワードを使用している場合、含まれているクラスまたは構造体にも、その Class
または Structure
ステートメントの直後に 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. Implements
ステートメントには、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
).
注意
ラムダ式を使用して、関数式をインラインで定義できます。You can use lambda expressions to define function expressions inline. 詳細については、「関数式」と「ラムダ式」を参照してください。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 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
Exit Function
および Return
ステートメントでは、Function
プロシージャがすぐに終了します。The Exit Function
and Return
statements cause an immediate exit from a Function
procedure. 任意の数の Exit Function
および Return
ステートメントをプロシージャ内の任意の場所に記述でき、Exit Function
ステートメントと Return
ステートメントを混在させることができます。Any number of Exit Function
and Return
statements can appear anywhere in the procedure, and you can mix Exit Function
and Return
statements.
name
に値を代入せずに Exit Function
を使用すると、プロシージャから、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
プロシージャは、Sqrt
、Cos
、ChrW
などの任意のライブラリ関数を呼び出すのと同じ方法で呼び出します。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
Async 機能を使用することによって、明示的なコールバックを使用せずに、または複数の関数やラムダ式にわたって手動でコードを分割することなく、非同期メソッドを呼び出すことができます。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.
注意
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> または Task を指定できます。An 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.
Async
関数で、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 ステートメントを使用して、各要素を 1 回に 1 つ返します。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. 次回、iterator 関数が呼び出されると、この位置から実行が再開されます。Execution is restarted from that location the next time the iterator function is called.
For Each...Next ステートメントを使用して、クライアント コードから反復子を呼び出します。You call an iterator from client code by using a For Each…Next statement.
iterator 関数の戻り値の型には、IEnumerable、IEnumerable<T>、IEnumerator、または IEnumerator<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. 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
次の例で、DelayAsync
は、戻り値の型が Task<TResult> である Async
Function
です。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)
であるため、DoSomethingAsync
内の Await
式を評価すると整数が生成されます。Because the return type is Task(Of Integer)
, the evaluation of the Await
expression in DoSomethingAsync
produces an integer. これは、ステートメント Dim result As Integer = Await delayTask
に示しています。This is demonstrated in this statement: Dim result As Integer = Await delayTask
.
startButton_Click
プロシージャは、Async Sub
プロシージャの一例です。The 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
プロシージャは、Await
式を使用しているため、Async
修飾子を使用して定義する必要があります。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
- Sub ステートメントSub Statement
- Function プロシージャFunction Procedures
- パラメーター リストParameter List
- Dim ステートメントDim Statement
- Call ステートメントCall Statement
- OfOf
- パラメーター配列Parameter Arrays
- 方法: ジェネリック クラスを使用するHow to: Use a Generic Class
- プロシージャのトラブルシューティングTroubleshooting Procedures
- ラムダ式Lambda Expressions
- Function 式Function Expression