MethodBase.Invoke 메서드

정의

MethodInfo 인스턴스에 의해 반영된 메서드 또는 생성자를 호출합니다.

오버로드

Name Description
Invoke(Object, Object[])

지정된 매개 변수를 사용하여 현재 인스턴스가 나타내는 메서드 또는 생성자를 호출합니다.

Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

파생 클래스에서 재정의되는 경우 지정된 매개 변수를 사용하여 반영된 메서드 또는 생성자를 호출합니다.

Invoke(Object, Object[])

Source:
MethodBase.cs
Source:
MethodBase.cs
Source:
MethodBase.cs
Source:
MethodBase.cs
Source:
MethodBase.cs

지정된 매개 변수를 사용하여 현재 인스턴스가 나타내는 메서드 또는 생성자를 호출합니다.

public:
 virtual System::Object ^ Invoke(System::Object ^ obj, cli::array <System::Object ^> ^ parameters);
public:
 System::Object ^ Invoke(System::Object ^ obj, cli::array <System::Object ^> ^ parameters);
public virtual object Invoke(object obj, object[] parameters);
public object? Invoke(object? obj, object?[]? parameters);
public object Invoke(object obj, object[] parameters);
abstract member Invoke : obj * obj[] -> obj
override this.Invoke : obj * obj[] -> obj
member this.Invoke : obj * obj[] -> obj
Public Overridable Function Invoke (obj As Object, parameters As Object()) As Object
Public Function Invoke (obj As Object, parameters As Object()) As Object

매개 변수

obj
Object

메서드 또는 생성자를 호출할 개체입니다. 메서드가 정적이면 이 인수는 무시됩니다. 생성자가 정적이면 이 인수 또는 null 생성자를 정의하는 클래스의 인스턴스여야 합니다.

parameters
Object[]

호출된 메서드 또는 생성자에 대한 인수 목록입니다. 호출할 메서드 또는 생성자의 매개 변수와 숫자, 순서 및 형식이 동일한 개체의 배열입니다. 매개 변수 parameters 가 없으면 .이어야 null합니다.

이 인스턴스에서 나타내는 메서드 또는 생성자가 매개 변수(ByRefVisual Basic)를 사용하는 ref 경우 이 함수를 사용하여 메서드 또는 생성자를 호출하기 위해 해당 매개 변수에 특별한 특성이 필요하지 않습니다. 값으로 명시적으로 초기화되지 않은 이 배열의 모든 개체에는 해당 개체 형식의 기본값이 포함됩니다. 참조 형식 요소의 경우 이 값은 .입니다 null. 값 형식 요소의 경우 기본값은 특정 요소 형식에 따라 0, 0.0 또는 false입니다.

반품

호출된 메서드 null 또는 생성자의 경우 반환 값을 포함하는 개체입니다.

구현

예외

obj 매개 변수가 null 있고 메서드가 정적이지 않습니다.

-또는-

메서드가 .의 obj클래스에 의해 선언되거나 상속되지 않습니다.

-또는-

정적 생성자가 호출되며 objnull 생성자를 선언한 클래스의 인스턴스도 아닙니다.

배열의 parameters 요소가 이 인스턴스에 의해 반영된 메서드 또는 생성자의 서명과 일치하지 않습니다.

호출된 메서드 또는 생성자가 예외를 throw합니다.

-또는-

현재 인스턴스는 DynamicMethod 확인되지 않는 코드를 포함하는 인스턴스입니다. "비고에서 DynamicMethod에 대한 \"확인\" 섹션을 참조하세요."

배열에 parameters 올바른 인수 수가 없습니다.

호출자에게 현재 인스턴스가 나타내는 메서드 또는 생성자를 실행할 수 있는 권한이 없습니다.

메서드를 선언하는 형식은 열린 제네릭 형식입니다. 즉, ContainsGenericParameters 선언 형식에 대한 속성이 반환 true 됩니다.

현재 인스턴스는 .입니다 MethodBuilder.

예제

다음 코드 예제에서는 리플렉션을 사용하는 동적 메서드 조회를 보여 줍니다. 지연 바인딩은 재정의 MethodInfo 를 확인할 수 없으므로 기본 클래스의 개체를 사용하여 파생 클래스에서 재정의된 메서드를 호출할 수 없습니다.

using System;
using System.Reflection;

public class MagicClass
{
    private int magicBaseValue;

    public MagicClass()
    {
        magicBaseValue = 9;
    }

    public int ItsMagic(int preMagic)
    {
        return preMagic * magicBaseValue;
    }
}

public class TestMethodInfo
{
    public static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        Type magicType = Type.GetType("MagicClass");
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
        object magicClassObject = magicConstructor.Invoke(new object[]{});

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
        object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

        Console.WriteLine("MethodInfo.Invoke() Example\n");
        Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
    }
}

// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900
Imports System.Reflection

Public Class MagicClass
    Private magicBaseValue As Integer

    Public Sub New()
        magicBaseValue = 9
    End Sub

    Public Function ItsMagic(preMagic As Integer) As Integer
        Return preMagic * magicBaseValue
    End Function
End Class

Public Class TestMethodInfo
    Public Shared Sub Main()
        ' Get the constructor and create an instance of MagicClass

        Dim magicType As Type = Type.GetType("MagicClass")
        Dim magicConstructor As ConstructorInfo = magicType.GetConstructor(Type.EmptyTypes)
        Dim magicClassObject As Object = magicConstructor.Invoke(New Object(){})

        ' Get the ItsMagic method and invoke with a parameter value of 100

        Dim magicMethod As MethodInfo = magicType.GetMethod("ItsMagic")
        Dim magicValue As Object = magicMethod.Invoke(magicClassObject, New Object(){100})

        Console.WriteLine("MethodInfo.Invoke() Example" + Environment.NewLine)
        Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue)
    End Sub
End Class

' The example program gives the following output:
'
' MethodInfo.Invoke() Example
'
' MagicClass.ItsMagic() returned: 900

설명

이 메서드는 메서드 오버로드를 Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) 호출하여 전달 DefaultinvokeAttr 및 전달합니다 nullbinderculture.

호출된 메서드가 예외를 throw하는 경우 메서드는 Exception.GetBaseException 원래 예외를 반환합니다.

개체를 사용하여 정적 메서드를 MethodInfo 호출하려면 다음을 전달 null 합니다 obj.

메모

이 메서드 오버로드를 사용하여 인스턴스 생성자를 호출하는 경우 제공된 obj 개체가 다시 초기화됩니다. 즉, 모든 인스턴스 이니셜라이저가 실행됩니다. 반환 값은 .입니다 null. 클래스 생성자가 호출되면 클래스가 다시 초기화됩니다. 즉, 모든 클래스 이니셜라이저가 실행됩니다. 반환 값은 .입니다 null.

메모

이 메서드는 호출자가 플래그를 ReflectionPermission 사용하여 부여된 ReflectionPermissionFlag.RestrictedMemberAccess 경우 및 비공용 멤버의 권한 부여 집합이 호출자의 권한 부여 집합 또는 해당 하위 집합으로 제한되는 경우 비공용 멤버에 액세스하는 데 사용할 수 있습니다. (리플렉션에 대한 보안 고려 사항 참조) 이 기능을 사용하려면 애플리케이션이 .NET Framework 3.5 이상을 대상으로 해야 합니다.

반영된 메서드의 매개 변수가 값 형식이고 해당 인수가 있는 parameters 경우 런타임은 null값 형식의 초기화된 인스턴스를 0으로 전달합니다.

추가 정보

적용 대상

Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

Source:
MethodBase.cs
Source:
MethodBase.cs
Source:
MethodBase.cs
Source:
MethodBase.cs
Source:
MethodBase.cs

파생 클래스에서 재정의되는 경우 지정된 매개 변수를 사용하여 반영된 메서드 또는 생성자를 호출합니다.

public:
 abstract System::Object ^ Invoke(System::Object ^ obj, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ parameters, System::Globalization::CultureInfo ^ culture);
public abstract object? Invoke(object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? parameters, System.Globalization.CultureInfo? culture);
public abstract object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture);
abstract member Invoke : obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj
Public MustOverride Function Invoke (obj As Object, invokeAttr As BindingFlags, binder As Binder, parameters As Object(), culture As CultureInfo) As Object

매개 변수

obj
Object

메서드 또는 생성자를 호출할 개체입니다. 메서드가 정적이면 이 인수는 무시됩니다. 생성자가 정적이면 이 인수 또는 null 생성자를 정의하는 클래스의 인스턴스여야 합니다.

invokeAttr
BindingFlags

에서 0개 이상의 비트 플래그 BindingFlags를 조합한 비트 마스크입니다.

binder
Binder

리플렉션을 통해 바인딩, 인수 형식 강제 변환, 멤버 호출 및 개체 검색 MemberInfo 을 사용하도록 설정하는 개체입니다. 이 binder경우 null 기본 바인더가 사용됩니다.

parameters
Object[]

호출된 메서드 또는 생성자에 대한 인수 목록입니다. 호출할 메서드 또는 생성자의 매개 변수와 숫자, 순서 및 형식이 동일한 개체의 배열입니다. 매개 변수가 없으면 다음과 여야 합니다 null.

이 인스턴스에서 나타내는 메서드 또는 생성자가 ByRef 매개 변수를 사용하는 경우 이 함수를 사용하여 메서드 또는 생성자를 호출하기 위해 해당 매개 변수에 특별한 특성이 필요하지 않습니다. 값으로 명시적으로 초기화되지 않은 이 배열의 모든 개체에는 해당 개체 형식의 기본값이 포함됩니다. 참조 형식 요소의 경우 이 값은 .입니다 null. 값 형식 요소의 경우 이 값은 특정 요소 형식에 따라 0, 0.0 또는 false입니다.

culture
CultureInfo

형식의 CultureInfo 강제 변환을 제어하는 데 사용되는 인스턴스입니다. 이 nullCultureInfo 경우 현재 스레드에 대한 스레드가 사용됩니다. (예를 들어 1000 Double 이 다른 문화권에 의해 다르게 표현되므로 1000을 나타내는 문자열을 값으로 변환하는 데 필요합니다.)

반품

Object 호출된 메서드의 반환 값 또는 생성자의 경우 또는 nullnull 메서드의 반환 형식이 포함된 값입니다void. 메서드 또는 생성자를 Invoke 호출하기 전에 사용자에게 액세스 권한이 있는지 확인하고 매개 변수가 유효한지 확인합니다.

구현

예외

obj 매개 변수가 null 있고 메서드가 정적이지 않습니다.

-또는-

메서드가 .의 obj클래스에 의해 선언되거나 상속되지 않습니다.

-또는-

정적 생성자가 호출되며 objnull 생성자를 선언한 클래스의 인스턴스도 아닙니다.

매개 변수 형식이 parameters 이 인스턴스에 의해 반영된 메서드 또는 생성자의 서명과 일치하지 않습니다.

배열에 parameters 올바른 인수 수가 없습니다.

호출된 메서드 또는 생성자가 예외를 throw합니다.

호출자에게 현재 인스턴스가 나타내는 메서드 또는 생성자를 실행할 수 있는 권한이 없습니다.

메서드를 선언하는 형식은 열린 제네릭 형식입니다. 즉, ContainsGenericParameters 선언 형식에 대한 속성이 반환 true 됩니다.

예제

다음 예제에서는 오버로드Type.InvokeMemberSystem.Reflection.Binder 사용하는 클래스의 모든 멤버를 보여 줍니다. private 메서드 CanConvertFrom 는 지정된 형식에 대해 호환되는 형식을 찾습니다. 사용자 지정 바인딩 시나리오에서 멤버를 호출하는 또 다른 예제는 동적으로 형식 로드 및 사용을 참조하세요.

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].PropertyType))
                    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);
    }
}
Imports System.Reflection
Imports System.Globalization

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

    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

    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).PropertyType) 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


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

    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
End Class


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
End Class

설명

이 메서드는 이 인스턴스에서 obj반영된 메서드를 동적으로 호출하고 지정된 매개 변수를 따라 전달합니다. 메서드가 정적이면 매개 변수가 obj 무시됩니다. 비정적 메서드의 경우 메서드 obj 를 상속하거나 선언하는 클래스의 인스턴스여야 하며 이 클래스와 동일한 형식이어야 합니다. 메서드에 매개 변수가 없으면 값 parameters 은 .이어야 null합니다. 그렇지 않은 경우 요소의 수, 형식 및 순서는 이 인스턴스에서 parameters 반영하는 메서드의 매개 변수 수, 형식 및 순서와 동일해야 합니다.

에 대한 호출 Invoke에서 선택적 매개 변수를 생략할 수 없습니다. 메서드를 호출하고 선택적 매개 변수를 생략하려면 대신 호출 Type.InvokeMember 합니다.

메모

이 메서드 오버로드를 사용하여 인스턴스 생성자를 호출하는 경우 제공된 obj 개체가 다시 초기화됩니다. 즉, 모든 인스턴스 이니셜라이저가 실행됩니다. 반환 값은 .입니다 null. 클래스 생성자가 호출되면 클래스가 다시 초기화됩니다. 즉, 모든 클래스 이니셜라이저가 실행됩니다. 반환 값은 .입니다 null.

값 단위 기본 매개 변수의 경우 일반 확대가 수행됩니다(예: Int16 -> Int32). 값별 전달 참조 매개 변수의 경우 일반 참조 확대가 허용됩니다(파생 클래스에서 기본 클래스로, 기본 클래스에서 인터페이스 형식으로). 그러나 참조 기본 매개 변수의 경우 형식이 정확히 일치해야 합니다. 참조별 통과 참조 매개 변수의 경우 일반 확대가 계속 적용됩니다.

예를 들어 이 인스턴스에 의해 반영된 메서드가 선언 public boolean Compare(String a, String b)parameters 된 경우 길이가 2parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2")인 배열 Objects 이어야 합니다.

현재 메서드의 매개 변수가 값 형식이고 해당 인수가 있는 parameters 경우 런타임은 null값 형식의 초기화된 인스턴스를 0으로 전달합니다.

리플렉션은 가상 메서드를 호출할 때 동적 메서드 조회를 사용합니다. 예를 들어 B 클래스가 A 클래스에서 상속되고 둘 다 M이라는 가상 메서드를 구현한다고 가정합니다. 이제 클래스 A에서 M을 MethodInfo 나타내는 개체가 있다고 가정합니다. 메서드를 Invoke 사용하여 B 형식의 개체에서 M을 호출하는 경우 리플렉션은 클래스 B에서 제공하는 구현을 사용합니다. B 형식의 개체가 A로 캐스팅되더라도 B 클래스에서 제공하는 구현이 사용됩니다(아래 코드 샘플 참조).

반면에 메서드가 가상이 아닌 경우 리플렉션은 대상으로 전달된 MethodInfo 개체의 형식에 관계없이 가져온 형식에 의해 지정된 구현을 사용합니다.

완전히 신뢰할 수 있는 코드에 대한 액세스 제한은 무시됩니다. 즉, 코드를 완전히 신뢰할 때마다 리플렉션을 통해 프라이빗 생성자, 메서드, 필드 및 속성에 액세스하고 호출할 수 있습니다.

호출된 메서드가 예외를 throw하는 경우 메서드는 Exception.GetBaseException 원래 예외를 반환합니다.

메모

이 메서드는 호출자가 플래그를 ReflectionPermission 사용하여 부여된 ReflectionPermissionFlag.RestrictedMemberAccess 경우 및 비공용 멤버의 권한 부여 집합이 호출자의 권한 부여 집합 또는 해당 하위 집합으로 제한되는 경우 비공용 멤버에 액세스하는 데 사용할 수 있습니다. (리플렉션에 대한 보안 고려 사항 참조) 이 기능을 사용하려면 애플리케이션이 .NET Framework 3.5 이상을 대상으로 해야 합니다.

추가 정보

적용 대상