次の方法で共有


MethodBase.Invoke メソッド (Object, BindingFlags, Binder, Object , CultureInfo)

派生クラスによってオーバーライドされた場合に、指定したパラメータでリフレクションされたメソッドまたはコンストラクタを呼び出します。

Overloads Public MustOverride Function Invoke( _
   ByVal obj As Object, _   ByVal invokeAttr As BindingFlags, _   ByVal binder As Binder, _   ByVal parameters() As Object, _   ByVal culture As CultureInfo _) As Object
[C#]
public abstract object Invoke(objectobj,BindingFlagsinvokeAttr,Binderbinder,object[] parameters,CultureInfoculture);
[C++]
public: virtual Object* Invoke(Object* obj,BindingFlagsinvokeAttr,Binder* binder,Object* parameters __gc[],CultureInfo* culture) = 0;
[JScript]
public abstract function Invoke(
   obj : Object,invokeAttr : BindingFlags,binder : Binder,parameters : Object[],culture : CultureInfo) : Object;

パラメータ

  • obj
    メソッドまたはコンストラクタを呼び出すオブジェクト。メソッドまたはコンストラクタが静的な場合、この引数は無視されます。

  • invokeAttr
    DefaultBindingNonPublic など、 BindingFlags の 0 個以上のビット フラグを組み合わせたビットマスク。binder が null 参照 (Visual Basic では Nothing) の場合、このパラメータが値 BindingFlags.DefaultBinding に割り当てられ、渡した値は無視されます。

  • binder
    バインディング、引数型の強制変換、メンバの呼び出し、およびリフレクションを通じた MemberInfo オブジェクトの取得を有効にするオブジェクト。binder が null 参照 (Visual Basic では Nothing) の場合は、既定のバインダが使用されます。

  • parameters
    呼び出すメソッドまたはコンストラクタの引数リスト。これは、呼び出すメソッドまたはコンストラクタのパラメータと同じ数、順序、および型のオブジェクトの配列です。パラメータがない場合は、 null 参照 (Visual Basic では Nothing) にします。

    このインスタンスで表されるメソッドまたはコンストラクタが ByRef パラメータをとる場合、この関数を使用してメソッドまたはコンストラクタを呼び出すために、このパラメータに特別な属性は必要ありません。この配列の中で、何らかの値で明示的に初期化されないオブジェクトには、そのオブジェクト型の既定値が格納されます。参照型の要素の場合、この値は null 参照 (Nothing) です。値型の要素の場合、この値は、実際の要素の型に応じて、0、0.0、または false となります。

  • culture
    型の強制変換を制御するために使用する CultureInfo のインスタンス。 null 参照 (Visual Basic では Nothing) の場合は、現在のスレッドの CultureInfo が使用されます。このインスタンスは、たとえば、1000 を表す文字列を double 値に変換する場合に必要です。これは、カルチャによって 1000 の表記が異なるためです。

戻り値

呼び出されたメソッドの戻り値を格納しているオブジェクト。コンストラクタの場合は、再初期化されたオブジェクト。メソッドの戻り値の型が void の場合は null 参照 (Visual Basic では Nothing) 。Invoke は、メソッドまたはコンストラクタを呼び出す前に、ユーザーに必要なアクセス許可が与えられていることを確認し、パラメータが有効かどうかを検査します。

例外

例外の種類 条件
TargetException obj パラメータが null 参照 (Visual Basic では Nothing) で、メソッドが静的でありません。

または

メソッドが、 obj のクラスで宣言も継承もされていません。

ArgumentException parameters パラメータの型が、このインスタンスでリフレクションされたメソッドまたはコンストラクタのシグネチャと一致しません。
TargetParameterCountException parameters 配列に、正しい数の引数の型が格納されていません。
TargetInvocationException 呼び出されたメソッドまたはコンストラクタが例外をスローします。
MethodAccessException 呼び出し元に、このコンストラクタを実行するためのアクセス許可がありません。

解説

obj のこのインスタンスでリフレクションされたメソッドを動的に呼び出し、指定したパラメータを渡します。メソッドが静的な場合、 obj パラメータは無視されます。非静的メソッドの場合、 obj は、そのメソッドを継承または宣言しているクラスのインスタンスで、このクラスと同じ型である必要があります。メソッドにパラメータがない場合、parameters の値は null 参照 (Visual Basic では Nothing) です。それ以外の場合、parameters の要素の数、型、および順序は、このインスタンスがリフレクションするメソッドのパラメータの数、型、および順序と同一である必要があります。

Invoke の呼び出しでは、オプションのパラメータを省略できません。オプションのパラメータを省略してメソッドを呼び出すには、 Type.InvokeMember を呼び出す必要があります。

値渡しのプリミティブ パラメータの場合は、通常の拡張が実行されます (Int16 -> Int32 など)。値渡しの参照パラメータの場合は、通常の参照拡張が許可されます (派生クラスから基本クラス、および基本クラスからインターフェイス型)。ただし、参照渡しのプリミティブ パラメータの場合は、型が正確に一致している必要があります。参照渡しの参照パラメータの場合は、通常の拡張が適用されます。

たとえば、このインスタンスでリフレクションされたメソッドが public boolean Compare(String a, String b) で宣言されている場合、 parameters は、 parameters[0] = newObject("SomeString1") and parameters[1] = new Object("SomeString2") のような長さが 2 の Objects の配列にする必要があります。

リフレクションは、仮想メソッドを呼び出すときに、動的メソッド検索を使用します。たとえば、クラス B がクラス A から継承され、どちらも M という仮想メソッドを実装しているとします。ここで、クラス A の M を表す MethodInfo オブジェクトがあるとします。Invoke メソッドを使用して型 B のオブジェクトの M を呼び出すと、リフレクションはクラス B で指定された実装を使用します。型 B のオブジェクトを A にキャストしても、クラス B で指定された実装が使用されます。次のコード例を参照してください。

一方、メソッドが非仮想の場合、リフレクションは対象として渡されたオブジェクトの型を無視して、 MethodInfo を取得した型で指定された実装を使用します。

完全に信頼されたコードでは、アクセス制限は無視されます。コードが完全に信頼されていると、リフレクションを使用して、プライベートなコンストラクタ、メソッド、フィールド、およびプロパティにアクセスし、それらを呼び出すことができます。

呼び出されたメソッドが例外をスローした場合、 TargetInvocationException.GetException は例外を返します。この実装は、 NotSupportedException をスローします。

使用例

[Visual Basic, C#, C++] Type.InvokeMember のオーバーロードを使用して System.Reflection.Binder クラスのすべてのメンバを使用する例を次に示します。プライベート メソッド CanConvertFrom を使用して、指定した型と互換性がある型を検索します。カスタム バインディング シナリオでメンバを呼び出す例については、「 型の動的な読み込みおよび使用 」を参照してください。

 
Imports System
Imports System.Reflection
Imports System.Globalization
Imports Microsoft.VisualBasic

Public Class MyBinder
    Inherits Binder
    Public Sub New()
        MyBase.new()
    End Sub 'New
    Private Class BinderState
        Public args() As Object
    End Class 'BinderState

    Public Overrides Function BindToField(ByVal bindingAttr As BindingFlags, ByVal match() As FieldInfo, ByVal value As Object, ByVal culture As CultureInfo) As FieldInfo
        If match Is Nothing Then
            Throw New ArgumentNullException("match")
        End If
        ' Get a field for which the value parameter can be converted to the specified field type.
        Dim i As Integer
        For i = 0 To match.Length - 1
            If Not (ChangeType(value, match(i).FieldType, culture) Is Nothing) Then
                Return match(i)
            End If
        Next i
        Return Nothing
    End Function 'BindToField

    Public Overrides Function BindToMethod(ByVal bindingAttr As BindingFlags, ByVal match() As MethodBase, ByRef args() As Object, ByVal modifiers() As ParameterModifier, ByVal culture As CultureInfo, ByVal names() As String, ByRef state As Object) As MethodBase
        ' Store the arguments to the method in a state object.
        Dim myBinderState As New BinderState()
        Dim arguments() As Object = New [Object](args.Length) {}
        args.CopyTo(arguments, 0)
        myBinderState.args = arguments
        state = myBinderState

        If match Is Nothing Then
            Throw New ArgumentNullException()
        End If
        ' Find a method that has the same parameters as those of args.
        Dim i As Integer
        For i = 0 To match.Length - 1
            ' Count the number of parameters that match.
            Dim count As Integer = 0
            Dim parameters As ParameterInfo() = match(i).GetParameters()
            ' Go on to the next method if the number of parameters do not match.
            If args.Length <> parameters.Length Then
                GoTo ContinueFori
            End If
            ' Match each of the parameters that the user expects the method to have.
            Dim j As Integer
            For j = 0 To args.Length - 1
                ' If names is not null, then reorder args.
                If Not (names Is Nothing) Then
                    If names.Length <> args.Length Then
                        Throw New ArgumentException("names and args must have the same number of elements.")
                    End If
                    Dim k As Integer
                    For k = 0 To names.Length - 1
                        If String.Compare(parameters(j).Name, names(k).ToString()) = 0 Then
                            args(j) = myBinderState.args(k)
                        End If
                    Next k
                End If ' Determine whether the types specified by the user can be converted to parameter type.
                If Not (ChangeType(args(j), parameters(j).ParameterType, culture) Is Nothing) Then
                    count += 1
                Else
                    Exit For
                End If
            Next j
            ' Determine whether the method has been found.
            If count = args.Length Then
                Return match(i)
            End If
ContinueFori:
        Next i
        Return Nothing
    End Function 'BindToMethod

    Public Overrides Function ChangeType(ByVal value As Object, ByVal myChangeType As Type, ByVal culture As CultureInfo) As Object
        ' Determine whether the value parameter can be converted to a value of type myType.
        If CanConvertFrom(value.GetType(), myChangeType) Then
            ' Return the converted object.
            Return Convert.ChangeType(value, myChangeType)
            ' Return null.
        Else
            Return Nothing
        End If
    End Function 'ChangeType

    Public Overrides Sub ReorderArgumentArray(ByRef args() As Object, ByVal state As Object)
        'Redimension the array to hold the state values.
        ReDim args(CType(state, BinderState).args.Length)
        ' Return the args that had been reordered by BindToMethod.
        CType(state, BinderState).args.CopyTo(args, 0)
    End Sub 'ReorderArgumentArray

    Public Overrides Function SelectMethod(ByVal bindingAttr As BindingFlags, ByVal match() As MethodBase, ByVal types() As Type, ByVal modifiers() As ParameterModifier) As MethodBase
        If match Is Nothing Then
            Throw New ArgumentNullException("match")
        End If
        Dim i As Integer
        For i = 0 To match.Length - 1
            ' Count the number of parameters that match.
            Dim count As Integer = 0
            Dim parameters As ParameterInfo() = match(i).GetParameters()
            ' Go on to the next method if the number of parameters do not match.
            If types.Length <> parameters.Length Then
                GoTo ContinueFori
            End If
            ' Match each of the parameters that the user expects the method to have.
            Dim j As Integer
            For j = 0 To types.Length - 1
                ' Determine whether the types specified by the user can be converted to parameter type.
                If CanConvertFrom(types(j), parameters(j).ParameterType) Then
                    count += 1
                Else
                    Exit For
                End If
            Next j ' Determine whether the method has been found.
            If count = types.Length Then
                Return match(i)
            End If
ContinueFori:
        Next i
        Return Nothing
    End Function 'SelectMethod
    Public Overrides Function SelectProperty(ByVal bindingAttr As BindingFlags, ByVal match() As PropertyInfo, ByVal returnType As Type, ByVal indexes() As Type, ByVal modifiers() As ParameterModifier) As PropertyInfo
        If match Is Nothing Then
            Throw New ArgumentNullException("match")
        End If
        Dim i As Integer
        For i = 0 To match.Length - 1
            ' Count the number of indexes that match.
            Dim count As Integer = 0
            Dim parameters As ParameterInfo() = match(i).GetIndexParameters()

            ' Go on to the next property if the number of indexes do not match.
            If indexes.Length <> parameters.Length Then
                GoTo ContinueFori
            End If
            ' Match each of the indexes that the user expects the property to have.
            Dim j As Integer
            For j = 0 To indexes.Length - 1
                ' Determine whether the types specified by the user can be converted to index type.
                If CanConvertFrom(indexes(j), parameters(j).ParameterType) Then
                    count += 1
                Else
                    Exit For
                End If
            Next j ' Determine whether the property has been found.
            If count = indexes.Length Then
                ' Determine whether the return type can be converted to the properties type.
                If CanConvertFrom(returnType, match(i).GetType()) Then
                    Return match(i)
                Else
                    GoTo ContinueFori
                End If
            End If
ContinueFori:
        Next i
        Return Nothing
    End Function 'SelectProperty

    ' Determine whether type1 can be converted to type2. Check only for primitive types.
    Private Function CanConvertFrom(ByVal type1 As Type, ByVal type2 As Type) As Boolean
        If type1.IsPrimitive And type2.IsPrimitive Then
            Dim typeCode1 As TypeCode = Type.GetTypeCode(type1)
            Dim typeCode2 As TypeCode = Type.GetTypeCode(type2)
            ' If both type1 and type2 have same type, return true.
            If typeCode1 = typeCode2 Then
                Return True
            End If ' Possible conversions from Char follow.
            If typeCode1 = TypeCode.Char Then
                Select Case typeCode2
                    Case TypeCode.UInt16
                        Return True
                    Case TypeCode.UInt32
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Byte follow.
            If typeCode1 = TypeCode.Byte Then
                Select Case typeCode2
                    Case TypeCode.Char
                        Return True
                    Case TypeCode.UInt16
                        Return True
                    Case TypeCode.Int16
                        Return True
                    Case TypeCode.UInt32
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from SByte follow.
            If typeCode1 = TypeCode.SByte Then
                Select Case typeCode2
                    Case TypeCode.Int16
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from UInt16 follow.
            If typeCode1 = TypeCode.UInt16 Then
                Select Case typeCode2
                    Case TypeCode.UInt32
                        Return True
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Int16 follow.
            If typeCode1 = TypeCode.Int16 Then
                Select Case typeCode2
                    Case TypeCode.Int32
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from UInt32 follow.
            If typeCode1 = TypeCode.UInt32 Then
                Select Case typeCode2
                    Case TypeCode.UInt64
                        Return True
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Int32 follow.
            If typeCode1 = TypeCode.Int32 Then
                Select Case typeCode2
                    Case TypeCode.Int64
                        Return True
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from UInt64 follow.
            If typeCode1 = TypeCode.UInt64 Then
                Select Case typeCode2
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Int64 follow.
            If typeCode1 = TypeCode.Int64 Then
                Select Case typeCode2
                    Case TypeCode.Single
                        Return True
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If ' Possible conversions from Single follow.
            If typeCode1 = TypeCode.Single Then
                Select Case typeCode2
                    Case TypeCode.Double
                        Return True
                    Case Else
                        Return False
                End Select
            End If
        End If
        Return False
    End Function 'CanConvertFrom
End Class 'MyBinder


Public Class MyClass1
    Public myFieldB As Short
    Public myFieldA As Integer

    Public Overloads Sub MyMethod(ByVal i As Long, ByVal k As Char)
        Console.WriteLine(ControlChars.NewLine & "This is MyMethod(long i, char k).")
    End Sub 'MyMethod

    Public Overloads Sub MyMethod(ByVal i As Long, ByVal j As Long)
        Console.WriteLine(ControlChars.NewLine & "This is MyMethod(long i, long j).")
    End Sub 'MyMethod
End Class 'MyClass1


Public Class Binder_Example
    Public Shared Sub Main()
        ' Get the type of MyClass1.
        Dim myType As Type = GetType(MyClass1)
        ' Get the instance of MyClass1.
        Dim myInstance As New MyClass1()
        Console.WriteLine(ControlChars.Cr & "Displaying the results of using the MyBinder binder.")
        Console.WriteLine()
        ' Get the method information for MyMethod.
        Dim myMethod As MethodInfo = myType.GetMethod("MyMethod", BindingFlags.Public Or BindingFlags.Instance, New MyBinder(), New Type() {GetType(Short), GetType(Short)}, Nothing)
        Console.WriteLine(MyMethod)
        ' Invoke MyMethod.
        myMethod.Invoke(myInstance, BindingFlags.InvokeMethod, New MyBinder(), New [Object]() {CInt(32), CInt(32)}, CultureInfo.CurrentCulture)
    End Sub 'Main
End Class 'Binder_Example

[C#] 
using System;
using System.Reflection;
using System.Globalization;

public class MyBinder : Binder 
{
    public MyBinder() : base()
    {
    }
    private class BinderState
    {
        public object[] args;
    }
    public override FieldInfo BindToField(
        BindingFlags bindingAttr,
        FieldInfo[] match,
        object value,
        CultureInfo culture
        )
    {
        if(match == null)
            throw new ArgumentNullException("match");
        // Get a field for which the value parameter can be converted to the specified field type.
        for(int i = 0; i < match.Length; i++)
            if(ChangeType(value, match[i].FieldType, culture) != null)
                return match[i];
        return null;
    }
    public override MethodBase BindToMethod(
        BindingFlags bindingAttr,
        MethodBase[] match,
        ref object[] args,
        ParameterModifier[] modifiers,
        CultureInfo culture,
        string[] names,
        out object state
        )
    {
        // Store the arguments to the method in a state object.
        BinderState myBinderState = new BinderState();
        object[] arguments = new Object[args.Length];
        args.CopyTo(arguments, 0);
        myBinderState.args = arguments;
        state = myBinderState;
        if(match == null)
            throw new ArgumentNullException();
        // Find a method that has the same parameters as those of the args parameter.
        for(int i = 0; i < match.Length; i++)
        {
            // Count the number of parameters that match.
            int count = 0;
            ParameterInfo[] parameters = match[i].GetParameters();
            // Go on to the next method if the number of parameters do not match.
            if(args.Length != parameters.Length)
                continue;
            // Match each of the parameters that the user expects the method to have.
            for(int j = 0; j < args.Length; j++)
            {
                // If the names parameter is not null, then reorder args.
                if(names != null)
                {
                    if(names.Length != args.Length)
                        throw new ArgumentException("names and args must have the same number of elements.");
                    for(int k = 0; k < names.Length; k++)
                        if(String.Compare(parameters[j].Name, names[k].ToString()) == 0)
                            args[j] = myBinderState.args[k];
                }
                // Determine whether the types specified by the user can be converted to the parameter type.
                if(ChangeType(args[j], parameters[j].ParameterType, culture) != null)
                    count += 1;
                else
                    break;
            }
            // Determine whether the method has been found.
            if(count == args.Length)
                return match[i];
        }
        return null;
    }
    public override object ChangeType(
        object value,
        Type myChangeType,
        CultureInfo culture
        )
    {
        // Determine whether the value parameter can be converted to a value of type myType.
        if(CanConvertFrom(value.GetType(), myChangeType))
            // Return the converted object.
            return Convert.ChangeType(value, myChangeType);
        else
            // Return null.
            return null;
    }
    public override void ReorderArgumentArray(
        ref object[] args,
        object state
        )
    {
        // Return the args that had been reordered by BindToMethod.
        ((BinderState)state).args.CopyTo(args, 0);
    }
    public override MethodBase SelectMethod(
        BindingFlags bindingAttr,
        MethodBase[] match,
        Type[] types,
        ParameterModifier[] modifiers
        )
    {
        if(match == null)
            throw new ArgumentNullException("match");
        for(int i = 0; i < match.Length; i++)
        {
            // Count the number of parameters that match.
            int count = 0; 
            ParameterInfo[] parameters = match[i].GetParameters();
            // Go on to the next method if the number of parameters do not match.
            if(types.Length != parameters.Length)
                continue;
            // Match each of the parameters that the user expects the method to have.
            for(int j = 0; j < types.Length; j++)
                // Determine whether the types specified by the user can be converted to parameter type.
                if(CanConvertFrom(types[j], parameters[j].ParameterType))
                    count += 1;
                else
                    break;
            // Determine whether the method has been found.
            if(count == types.Length)
                return match[i];
        }
        return null;
    }
    public override PropertyInfo SelectProperty(
        BindingFlags bindingAttr,
        PropertyInfo[] match,
        Type returnType,
        Type[] indexes,
        ParameterModifier[] modifiers
        )
    {
        if(match == null)
            throw new ArgumentNullException("match");
        for(int i = 0; i < match.Length; i++)
        {
            // Count the number of indexes that match.
            int count = 0;
            ParameterInfo[] parameters = match[i].GetIndexParameters();
            // Go on to the next property if the number of indexes do not match.
            if(indexes.Length != parameters.Length)
                continue;
            // Match each of the indexes that the user expects the property to have.
            for(int j = 0; j < indexes.Length; j++)
                // Determine whether the types specified by the user can be converted to index type.
                if(CanConvertFrom(indexes[j], parameters[j].ParameterType))
                    count += 1;
                else
                    break;
            // Determine whether the property has been found.
            if(count == indexes.Length)
                // Determine whether the return type can be converted to the properties type.
                if(CanConvertFrom(returnType, match[i].GetType()))
                    return match[i];
                else
                    continue;
        }
        return null;
    }
    // Determines whether type1 can be converted to type2. Check only for primitive types.
    private bool CanConvertFrom(Type type1, Type type2)
    {
        if(type1.IsPrimitive && type2.IsPrimitive)
        {
            TypeCode typeCode1 = Type.GetTypeCode(type1);
            TypeCode typeCode2 = Type.GetTypeCode(type2);
            // If both type1 and type2 have the same type, return true.
            if(typeCode1 == typeCode2)
                return true;
            // Possible conversions from Char follow.
            if(typeCode1 == TypeCode.Char)
                switch(typeCode2)
                {
                    case TypeCode.UInt16 : return true;
                    case TypeCode.UInt32 : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Byte follow.
            if(typeCode1 == TypeCode.Byte)
                switch(typeCode2)
                {
                    case TypeCode.Char   : return true;
                    case TypeCode.UInt16 : return true;
                    case TypeCode.Int16  : return true;
                    case TypeCode.UInt32 : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from SByte follow.
            if(typeCode1 == TypeCode.SByte)
                switch(typeCode2)
                {
                    case TypeCode.Int16  : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from UInt16 follow.
            if(typeCode1 == TypeCode.UInt16)
                switch(typeCode2)
                {
                    case TypeCode.UInt32 : return true;
                    case TypeCode.Int32  : return true;
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Int16 follow.
            if(typeCode1 == TypeCode.Int16)
                switch(typeCode2)
                {
                    case TypeCode.Int32  : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from UInt32 follow.
            if(typeCode1 == TypeCode.UInt32)
                switch(typeCode2)
                {
                    case TypeCode.UInt64 : return true;
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Int32 follow.
            if(typeCode1 == TypeCode.Int32)
                switch(typeCode2)
                {
                    case TypeCode.Int64  : return true;
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from UInt64 follow.
            if(typeCode1 == TypeCode.UInt64)
                switch(typeCode2)
                {
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Int64 follow.
            if(typeCode1 == TypeCode.Int64)
                switch(typeCode2)
                {
                    case TypeCode.Single : return true;
                    case TypeCode.Double : return true;
                    default              : return false;
                }
            // Possible conversions from Single follow.
            if(typeCode1 == TypeCode.Single)
                switch(typeCode2)
                {
                    case TypeCode.Double : return true;
                    default              : return false;
                }
        }
        return false;
    }
}
public class MyClass1
{
    public short myFieldB;
    public int myFieldA; 
    public void MyMethod(long i, char k)
    {
        Console.WriteLine("\nThis is MyMethod(long i, char k)");
    }
    public void MyMethod(long i, long j)
    {
        Console.WriteLine("\nThis is MyMethod(long i, long j)");
    }
}
public class Binder_Example
{
    public static void Main()
    {
        // Get the type of MyClass1.
        Type myType = typeof(MyClass1);
        // Get the instance of MyClass1.
        MyClass1 myInstance = new MyClass1();
        Console.WriteLine("\nDisplaying the results of using the MyBinder binder.\n");
        // Get the method information for MyMethod.
        MethodInfo myMethod = myType.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance,
            new MyBinder(), new Type[] {typeof(short), typeof(short)}, null);
        Console.WriteLine(myMethod);
        // Invoke MyMethod.
        myMethod.Invoke(myInstance, BindingFlags.InvokeMethod, new MyBinder(), new Object[] {(int)32, (int)32}, CultureInfo.CurrentCulture);
    }
}

[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Reflection;
using namespace System::Globalization;
using namespace System::Runtime::InteropServices;

public __gc class MyBinder : public Binder
{
public:
   MyBinder() : Binder()
   {
   }
private:
   __gc class BinderState 
   {
   public:
      Object* args[];
   };
public:
   FieldInfo* BindToField(
      BindingFlags bindingAttr,
      FieldInfo* match[],
      Object* value,
      CultureInfo* culture)
   {
      if (match == 0)
         throw new ArgumentNullException(S"match");
      // Get a field for which the value parameter can be converted to the specified field type.
      for (int i = 0; i < match->Length; i++)
         if (ChangeType(value, match[i]->FieldType, culture) != 0)
            return match[i];
      return 0;
   }
   virtual MethodBase* BindToMethod(
      BindingFlags bindingAttr,
      MethodBase* match[],
      Object* (*args)[],
      ParameterModifier modifiers[],
      CultureInfo* culture,
      String* names[],
      [Out] Object** state)
   {
      // Store the arguments to the method in a state Object*.
      BinderState* myBinderState = new BinderState();
      Object* arguments[] = new Object*[(*args)->Length];
      (*args)->CopyTo(arguments, 0);
      myBinderState->args = arguments;
      *state = myBinderState;
      if (match == 0)
         throw new ArgumentNullException();
      // Find a method that has the same parameters as those of the args parameter.
      for (int i = 0; i < match->Length; i++) {
         // Count the number of parameters that match.
         int count = 0;
         ParameterInfo* parameters[] = match[i]->GetParameters();
         // Go on to the next method if the number of parameters do not match.
         if ((*args)->Length != parameters->Length)
            continue;
         // Match each of the parameters that the user expects the method to have.
         for (int j = 0; j < (*args)->Length; j++) {
            // If the names parameter is not 0, then reorder args.
            if (names != 0) {
               if (names->Length != (*args)->Length)
                  throw new ArgumentException(S"names and args must have the same number of elements.");
               for (int k = 0; k < names->Length; k++)
                  if (String::Compare(parameters[j]->Name, names[k]) == 0)
                     (*args)[j] = myBinderState->args->Item[k];
            }
            // Determine whether the types specified by the user can be converted to the parameter type.
            if (ChangeType(args[j], parameters[j]->ParameterType, culture) != 0)
               count += 1;
            else
               break;
         }
         // Determine whether the method has been found.
         if (count == (*args)->Length)
            return match[i];
      }
      return 0;
   }
   Object* ChangeType(Object* value, Type* myChangeType, CultureInfo* culture)
   {
      // Determine whether the value parameter can be converted to a value of type myType.
      if (CanConvertFrom(value->GetType(), myChangeType))
         // Return the converted Object*.
         return Convert::ChangeType(value, myChangeType);
      else
         // Return 0.
         return 0;
   }
   void ReorderArgumentArray(Object* (*args) __gc[], Object* state)
   {
      // Return the args that had been reordered by BindToMethod.
      (__try_cast<BinderState*>(state))->args->CopyTo((*args), 0);
   }
   MethodBase* SelectMethod(
      BindingFlags bindingAttr,
      MethodBase* match[],
      Type* types[],
      ParameterModifier modifiers[])
   {
      if (match == 0)
         throw new ArgumentNullException(S"match");
      for (int i = 0; i < match->Length; i++) {
         // Count the number of parameters that match.
         int count = 0; 
         ParameterInfo* parameters[] = match[i]->GetParameters();
         // Go on to the next method if the number of parameters do not match.
         if (types->Length != parameters->Length)
            continue;
         // Match each of the parameters that the user expects the method to have.
         for (int j = 0; j < types->Length; j++)
            // Determine whether the types specified by the user can be converted to parameter type.
            if (CanConvertFrom(types[j], parameters[j]->ParameterType))
               count += 1;
            else
               break;
         // Determine whether the method has been found.
         if (count == types->Length)
            return match[i];
      }
      return 0;
   }
   PropertyInfo* SelectProperty(
      BindingFlags bindingAttr,
      PropertyInfo* match[],
      Type* returnType,
      Type* indexes[],
      ParameterModifier modifiers[])
   {
      if (match == 0)
         throw new ArgumentNullException(S"match");
      for (int i = 0; i < match->Length; i++) {
         // Count the number of indexes that match.
         int count = 0;
         ParameterInfo* parameters[] = match[i]->GetIndexParameters();
         // Go on to the next property if the number of indexes do not match.
         if (indexes->Length != parameters->Length)
            continue;
         // Match each of the indexes that the user expects the property to have.
         for (int j = 0; j < indexes->Length; j++)
            // Determine whether the types specified by the user can be converted to index type.
            if (CanConvertFrom(indexes[j], parameters[j]->ParameterType))
               count += 1;
            else
               break;
         // Determine whether the property has been found.
         if (count == indexes->Length)
            // Determine whether the return type can be converted to the properties type.
            if (CanConvertFrom(returnType, match[i]->GetType()))
               return match[i];
            else
               continue;
      }
      return 0;
   }
   // Determines whether type1 can be converted to type2. Check only for primitive types.
private:
   bool CanConvertFrom(Type* type1, Type* type2)
   {
      if (type1->IsPrimitive && type2->IsPrimitive)
      {
         TypeCode typeCode1 = Type::GetTypeCode(type1);
         TypeCode typeCode2 = Type::GetTypeCode(type2);
         // If both type1 and type2 have the same type, return true.
         if (typeCode1 == typeCode2)
            return true;
         // Possible conversions from Char follow.
         if (typeCode1 == TypeCode::Char){
            switch(typeCode2) {
               case TypeCode::UInt16 : return true;
               case TypeCode::UInt32 : return true;
               case TypeCode::Int32  : return true;
               case TypeCode::UInt64 : return true;
               case TypeCode::Int64  : return true;
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from Byte follow.
         if (typeCode1 == TypeCode::Byte){
            switch(typeCode2) {
               case TypeCode::Char   : return true;
               case TypeCode::UInt16 : return true;
               case TypeCode::Int16  : return true;
               case TypeCode::UInt32 : return true;
               case TypeCode::Int32  : return true;
               case TypeCode::UInt64 : return true;
               case TypeCode::Int64  : return true;
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from SByte follow.
         if (typeCode1 == TypeCode::SByte){
            switch(typeCode2) {
               case TypeCode::Int16  : return true;
               case TypeCode::Int32  : return true;
               case TypeCode::Int64  : return true;
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from UInt16 follow.
         if (typeCode1 == TypeCode::UInt16){
            switch(typeCode2) {
               case TypeCode::UInt32 : return true;
               case TypeCode::Int32  : return true;
               case TypeCode::UInt64 : return true;
               case TypeCode::Int64  : return true;
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from Int16 follow.
         if (typeCode1 == TypeCode::Int16){
            switch(typeCode2) {
               case TypeCode::Int32  : return true;
               case TypeCode::Int64  : return true;
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from UInt32 follow.
         if (typeCode1 == TypeCode::UInt32){
            switch(typeCode2) {
               case TypeCode::UInt64 : return true;
               case TypeCode::Int64  : return true;
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from Int32 follow.
         if (typeCode1 == TypeCode::Int32){
            switch(typeCode2) {
               case TypeCode::Int64  : return true;
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from UInt64 follow.
         if (typeCode1 == TypeCode::UInt64){
            switch(typeCode2) {
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from Int64 follow.
         if (typeCode1 == TypeCode::Int64){
            switch(typeCode2) {
               case TypeCode::Single : return true;
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
         // Possible conversions from Single follow.
         if (typeCode1 == TypeCode::Single){
            switch(typeCode2) {
               case TypeCode::Double : return true;
               default              : return false;
            }
         }
      }
      return false;
   }
};

public __gc class MyClass1
{
public:
   short myFieldB;
   int myFieldA; 
   void MyMethod(long i, char k)
   {
      Console::WriteLine(S"\nThis is MyMethod(long i, char k)");
   }
   void MyMethod(long i, long j)
   {
      Console::WriteLine(S"\nThis is MyMethod(long i, long j)");
   }
};

int main()
{
   // Get the type of MyClass1.
   Type* myType = __typeof(MyClass1);
   // Get the instance of MyClass1.
   MyClass1* myInstance = new MyClass1();
   Console::WriteLine(S"\nDisplaying the results of using the MyBinder binder.\n");
   // Get the method information for MyMethod.
   Type* types[] = {__typeof(short), __typeof(short)};
   MethodInfo* myMethod = myType->GetMethod(S"MyMethod",
      static_cast<BindingFlags>( BindingFlags::Public | BindingFlags::Instance ),
      new MyBinder(), types, 0);
   Console::WriteLine(myMethod);
   // Invoke MyMethod.
   Object* obj[] = {__box(32), __box(32)};
   myMethod->Invoke(myInstance, BindingFlags::InvokeMethod, new MyBinder(), obj, CultureInfo::CurrentCulture);
}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET, Common Language Infrastructure (CLI) Standard

.NET Framework セキュリティ:

参照

MethodBase クラス | MethodBase メンバ | System.Reflection 名前空間 | MethodBase.Invoke オーバーロードの一覧 | 型の動的な読み込みおよび使用 | InvokeMember