MethodBase.Invoke MethodBase.Invoke MethodBase.Invoke MethodBase.Invoke Method

定义

调用由此 MethodInfo 实例反射的方法或构造函数。Invokes the method or constructor reflected by this MethodInfo instance.

重载

Invoke(Object, Object[]) Invoke(Object, Object[]) Invoke(Object, Object[]) Invoke(Object, Object[])

使用指定参数调用由当前实例表示的方法或构造函数。Invokes the method or constructor represented by the current instance, using the specified parameters.

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

当在派生类中重写时,调用具有给定参数的反射的方法或构造函数。When overridden in a derived class, invokes the reflected method or constructor with the given parameters.

Invoke(Object, Object[]) Invoke(Object, Object[]) Invoke(Object, Object[]) Invoke(Object, Object[])

使用指定参数调用由当前实例表示的方法或构造函数。Invokes the method or constructor represented by the current instance, using the specified parameters.

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

参数

obj
Object Object Object Object

在其上调用方法或构造函数的对象。The object on which to invoke the method or constructor. 如果方法是静态的,则忽略此参数。If a method is static, this argument is ignored. 如果构造函数是静态的,则此参数必须是 null 或定义构造函数的类的实例。If a constructor is static, this argument must be null or an instance of the class that defines the constructor.

parameters
Object[]

调用方法或构造函数的参数列表。An argument list for the invoked method or constructor. 此对象数组在数量、顺序和类型方面与要调用的方法或构造函数的参数相同。This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. 如果不存在任何参数,则 parameters 应为 nullIf there are no parameters, parameters should be null.

如果由此实例表示的方法或构造函数采用了 ref 参数(在 Visual Basic 中为 ByRef),那么此参数不需要特殊属性来通过此函数调用此方法或构造函数。If the method or constructor represented by this instance takes a ref parameter (ByRef in Visual Basic), no special attribute is required for that parameter in order to invoke the method or constructor using this function. 此数组中未使用值显式初始化的任何对象都将包含该对象类型的默认值。Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. 对于引用类型元素,此值为 nullFor reference-type elements, this value is null. 对于值类型元素,此值为 0、0.0 或 false,具体取决于特定的元素类型。For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.

返回

一个包含已调用方法的返回值或包含已调用构造函数的 null 的对象。An object containing the return value of the invoked method, or null in the case of a constructor.

实现

异常

适用于 Windows 应用商店应用的 .NET可移植类库中,改为捕获 ExceptionIn the.NET for Windows Store apps or the Portable Class Library, catch Exception instead.

obj 参数为 null,且此方法不是静态方法。The obj parameter is null and the method is not static. -or- 该方法不由 obj 的类声明或继承。The method is not declared or inherited by the class of obj. -or- 调用静态构造函数,obj 既不是 null,也不是声明构造函数的类的实例。A static constructor is invoked, and obj is neither null nor an instance of the class that declared the constructor.

parameters 数组的元素与此实例反映的方法或构造函数的签名不匹配。The elements of the parameters array do not match the signature of the method or constructor reflected by this instance.

调用的方法或构造函数引发异常。The invoked method or constructor throws an exception.

-or- 当前实例是包含无法验证的代码的 DynamicMethodThe current instance is a DynamicMethod that contains unverifiable code. 请参阅“验证”部分中的 DynamicMethod 注释。See the "Verification" section in Remarks for DynamicMethod.

parameters 数组的参数数量不正确。The parameters array does not have the correct number of arguments.

适用于 Windows 应用商店应用的 .NET可移植类库中,改为捕获基类异常 MemberAccessExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

调用方没有执行由当前实例表示的方法或构造函数的权限。The caller does not have permission to execute the method or constructor that is represented by the current instance.

声明该方法的类型为开放式泛型类型。The type that declares the method is an open generic type. 也就是说,ContainsGenericParameters 属性为声明类型返回 trueThat is, the ContainsGenericParameters property returns true for the declaring type.

示例

下面的代码示例演示使用反射的动态方法查找。The following code example demonstrates dynamic method lookup using reflection. 请注意,不能使用MethodInfo基类中的对象调用派生类中的重写方法,因为后期绑定无法解析重写。Note that you cannot use the MethodInfo object from the base class to invoke the overridden method in the derived class, because late binding cannot resolve overrides.

using namespace System;
using namespace System::Reflection;

public ref class MagicClass
{
private:
    int magicBaseValue;

public:
    MagicClass()
    {
        magicBaseValue = 9;
    }

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

public ref 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(gcnew array<Object^>(0));

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

        MethodInfo^ magicMethod = magicType->GetMethod("ItsMagic");
        Object^ magicValue = magicMethod->Invoke(magicClassObject, gcnew array<Object^>(1){100});

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

int main()
{
    TestMethodInfo::Main();
}

// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900
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" + vbNewLine)
        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)调用方法重载, DefaultinvokeAttrnull binderculture传递 for 和。This is a convenience method that calls the Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) method overload, passing Default for invokeAttr and null for binder and culture.

如果调用的方法引发异常,则该Exception.GetBaseException方法将返回异常。If the invoked method throws an exception, the Exception.GetBaseException method returns the exception.

若要使用其MethodInfo对象调用静态方法,请传递obj null for。To invoke a static method using its MethodInfo object, pass null for obj.

备注

如果使用此方法重载来调用实例构造函数,则将重新初始化为obj提供的对象; 即,执行所有实例初始值设定项。If this method overload is used to invoke an instance constructor, the object supplied for obj is reinitialized; that is, all instance initializers are executed. 返回值为 nullThe return value is null. 如果调用类构造函数,则类将重新初始化;也就是说,执行所有类初始值设定项。If a class constructor is invoked, the class is reinitialized; that is, all class initializers are executed. 返回值为 nullThe return value is null.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,如果调用方已获得标志并且非公共成员的授予集限制为调用方的授予集或子集,则可以使用此方法访问非公共成员。 .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

如果当前方法的参数是值类型,而中parameters的相应参数为null,则运行时将传递值类型的零初始化实例。If a parameter of the current method is a value type, and the corresponding argument in parameters is null, the runtime passes a zero-initialized instance of the value type.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

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

当在派生类中重写时,调用具有给定参数的反射的方法或构造函数。When overridden in a derived class, invokes the reflected method or constructor with the given parameters.

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);
abstract member Invoke : obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj

参数

obj
Object Object Object Object

在其上调用方法或构造函数的对象。The object on which to invoke the method or constructor. 如果方法是静态的,则忽略此参数。If a method is static, this argument is ignored. 如果构造函数是静态的,则此参数必须是 null 或定义构造函数的类的实例。If a constructor is static, this argument must be null or an instance of the class that defines the constructor.

invokeAttr
BindingFlags BindingFlags BindingFlags BindingFlags

位屏蔽,它是 BindingFlags 的 0 个或多个位标志的组合。A bitmask that is a combination of 0 or more bit flags from BindingFlags. 如果 bindernull,则此参数赋值为 Default;因此,传入的任何值都被忽略。If binder is null, this parameter is assigned the value Default; thus, whatever you pass in is ignored.

binder
Binder Binder Binder Binder

一个对象,它启用绑定、对参数类型的强制、对成员的调用,以及通过反射对 MemberInfo 对象的检索。An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects via reflection. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

parameters
Object[]

调用方法或构造函数的参数列表。An argument list for the invoked method or constructor. 此对象数组在数量、顺序和类型方面与要调用的方法或构造函数的参数相同。This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. 如果没有参数,则此应为 nullIf there are no parameters, this should be null.

如果此实例表示的方法或构造函数采用 ByRef 参数,那么使用此函数调用该方法或构造函数时,对于该参数不需要特殊的特性。If the method or constructor represented by this instance takes a ByRef parameter, there is no special attribute required for that parameter in order to invoke the method or constructor using this function. 此数组中未使用值显式初始化的任何对象都将包含该对象类型的默认值。Any object in this array that is not explicitly initialized with a value will contain the default value for that object type. 对于引用类型元素,此值为 nullFor reference-type elements, this value is null. 对于值类型元素,此值为 0、0.0 或 false,具体取决于特定的元素类型。For value-type elements, this value is 0, 0.0, or false, depending on the specific element type.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

用于控制类型强制的 CultureInfo 的实例。An instance of CultureInfo used to govern the coercion of types. 如果这是 null,则使用当前线程的 CultureInfoIf this is null, the CultureInfo for the current thread is used. (例如,这对于将表示 1000 的 String 转换为 Double 值是必需的,因为不同的区域性以不同的方式表示 1000。)(This is necessary to convert a String that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures.)

返回

Object,包含被调用方法的返回值;如果调用的是构造函数,则为 null;如果方法的返回类型是 null,则为 voidAn Object containing the return value of the invoked method, or null in the case of a constructor, or null if the method's return type is void. 在调用方法或构造函数之前,Invoke 检查用户是否有访问权限并验证参数是否有效。Before calling the method or constructor, Invoke checks to see if the user has access permission and verifies that the parameters are valid.

实现

异常

obj 参数为 null,且此方法不是静态方法。The obj parameter is null and the method is not static.

-or- 该方法不由 obj 的类声明或继承。The method is not declared or inherited by the class of obj.

- 或 --or- 调用静态构造函数,obj 既不是 null,也不是声明构造函数的类的实例。A static constructor is invoked, and obj is neither null nor an instance of the class that declared the constructor.

parameters 参数的类型与此实例所反射的方法或构造函数的签名不匹配。The type of the parameters parameter does not match the signature of the method or constructor reflected by this instance.

parameters 数组的参数数量不正确。The parameters array does not have the correct number of arguments.

调用的方法或构造函数引发异常。The invoked method or constructor throws an exception.

调用方没有执行由当前实例表示的方法或构造函数的权限。The caller does not have permission to execute the method or constructor that is represented by the current instance.

声明该方法的类型为开放式泛型类型。The type that declares the method is an open generic type. 也就是说,ContainsGenericParameters 属性为声明类型返回 trueThat is, the ContainsGenericParameters property returns true for the declaring type.

示例

下面的示例使用的System.Reflection.Binder Type.InvokeMember重载演示类的所有成员。The following example demonstrates all members of the System.Reflection.Binder class using an overload of Type.InvokeMember. 私有方法CanConvertFrom查找给定类型的兼容类型。The private method CanConvertFrom finds compatible types for a given type. 有关在自定义绑定方案中调用成员的另一个示例,请参阅动态加载和使用类型For another example of invoking members in a custom binding scenario, see Dynamically Loading and Using Types.

using namespace System;
using namespace System::Reflection;
using namespace System::Globalization;
using namespace System::Runtime::InteropServices;
public ref class MyBinder: public Binder
{
public:
   MyBinder()
      : Binder()
   {}

private:
   ref class BinderState
   {
   public:
      array<Object^>^args;
   };

public:
   virtual FieldInfo^ BindToField( BindingFlags bindingAttr, array<FieldInfo^>^match, Object^ value, CultureInfo^ culture ) override
   {
      if ( match == nullptr )
            throw gcnew 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 ) != nullptr )
                  return match[ i ];

      return nullptr;
   }

   virtual MethodBase^ BindToMethod( BindingFlags bindingAttr, array<MethodBase^>^match, array<Object^>^%args, array<ParameterModifier>^ modifiers, CultureInfo^ culture, array<String^>^names, [Out]Object^% state ) override
   {
      // Store the arguments to the method in a state Object*.
      BinderState^ myBinderState = gcnew BinderState;
      array<Object^>^arguments = gcnew array<Object^>(args->Length);
      args->CopyTo( arguments, 0 );
      myBinderState->args = arguments;
      state = myBinderState;
      if ( match == nullptr )
            throw gcnew 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;
         array<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 != nullptr )
            {
               if ( names->Length != args->Length )
                              throw gcnew 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 ] ) == 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 ) != nullptr )
                        count += 1;
            else
                        break;
         }
         if ( count == args->Length )
                  return match[ i ];
      }
      return nullptr;
   }

   virtual Object^ ChangeType( Object^ value, Type^ myChangeType, CultureInfo^ culture ) override
   {
      // 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 nullptr;
   }

   virtual void ReorderArgumentArray( array<Object^>^%args, Object^ state ) override
   {
      // Return the args that had been reordered by BindToMethod.
      (safe_cast<BinderState^>(state))->args->CopyTo( args, 0 );
   }

   virtual MethodBase^ SelectMethod( BindingFlags bindingAttr, array<MethodBase^>^match, array<Type^>^types, array<ParameterModifier>^ modifiers ) override
   {
      if ( match == nullptr )
            throw gcnew ArgumentNullException( "match" );

      for ( int i = 0; i < match->Length; i++ )
      {
         // Count the number of parameters that match.
         int count = 0;
         array<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 nullptr;
   }

   virtual PropertyInfo^ SelectProperty( BindingFlags bindingAttr, array<PropertyInfo^>^match, Type^ returnType, array<Type^>^indexes, array<ParameterModifier>^ modifiers ) override
   {
      if ( match == nullptr )
            throw gcnew ArgumentNullException( "match" );

      for ( int i = 0; i < match->Length; i++ )
      {
         // Count the number of indexes that match.
         int count = 0;
         array<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 nullptr;
   }

private:

   // Determines whether type1 can be converted to type2. Check only for primitive types.
   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 ref class MyClass1
{
public:
   short myFieldB;
   int myFieldA;
   void MyMethod( long i, char k )
   {
      Console::WriteLine( "\nThis is MyMethod(long i, char k)" );
   }

   void MyMethod( long i, long j )
   {
      Console::WriteLine( "\nThis is MyMethod(long i, long j)" );
   }
};

int main()
{
   // Get the type of MyClass1.
   Type^ myType = MyClass1::typeid;

   // Get the instance of MyClass1.
   MyClass1^ myInstance = gcnew MyClass1;
   Console::WriteLine( "\nDisplaying the results of using the MyBinder binder.\n" );

   // Get the method information for MyMethod.
   array<Type^>^types = {short::typeid,short::typeid};
   MethodInfo^ myMethod = myType->GetMethod( "MyMethod", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance), gcnew MyBinder, types, nullptr );
   Console::WriteLine( myMethod );

   // Invoke MyMethod.
   array<Object^>^obj = {32,32};
   myMethod->Invoke( myInstance, BindingFlags::InvokeMethod, gcnew MyBinder, obj, CultureInfo::CurrentCulture );
}
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动态调用此实例反射的方法,并沿指定参数传递。Dynamically invokes the method reflected by this instance on obj, and passes along the specified parameters. 如果该方法是静态的, obj则忽略该参数。If the method is static, the obj parameter is ignored. 对于非静态方法, obj应为继承或声明方法的类的实例,并且必须与此类具有相同的类型。For non-static methods, obj should be an instance of a class that inherits or declares the method and must be the same type as this class. 如果该方法没有参数,则的parameters值应为。 nullIf the method has no parameters, the value of parameters should be null. 否则,中parameters元素的数量、类型和顺序应当与此实例所反射的方法的参数的数量、类型和顺序相同。Otherwise, the number, type, and order of elements in parameters should be identical to the number, type, and order of parameters for the method reflected by this instance.

在对的调用Invoke中,不能省略可选参数。You may not omit optional parameters in calls to Invoke. 若要调用省略可选参数的方法,应改Type.InvokeMember为调用。To invoke a method omitting optional parameters, you should call Type.InvokeMember instead.

备注

如果使用此方法重载来调用实例构造函数,则将重新初始化为obj提供的对象; 即,执行所有实例初始值设定项。If this method overload is used to invoke an instance constructor, the object supplied for obj is reinitialized; that is, all instance initializers are executed. 返回值为 nullThe return value is null. 如果调用类构造函数,则类将重新初始化;也就是说,执行所有类初始值设定项。If a class constructor is invoked, the class is reinitialized; that is, all class initializers are executed. 返回值为 nullThe return value is null.

对于按值传递的基元参数,将执行正常扩展(例如 Int16 > Int32)。For pass-by-value primitive parameters, normal widening is performed (Int16 -> Int32, for example). 对于按值传递引用参数,允许进行常规引用扩大(派生类到基类,并使用基类到接口类型)。For pass-by-value reference parameters, normal reference widening is allowed (derived class to base class, and base class to interface type). 但是,对于按引用传递的基元参数,类型必须完全匹配。However, for pass-by-reference primitive parameters, the types must match exactly. 对于按引用传递引用参数,正常扩展仍适用。For pass-by-reference reference parameters, the normal widening still applies.

例如,如果此实例反射的方法public boolean Compare(String a, String b)被声明为,则parameters Objects应为长度为2的parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2")数组,例如。For example, if the method reflected by this instance is declared as public boolean Compare(String a, String b), then parameters should be an array of Objects with length 2 such that parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2").

如果当前方法的参数是值类型,而中parameters的相应参数为null,则运行时将传递值类型的零初始化实例。If a parameter of the current method is a value type, and the corresponding argument in parameters is null, the runtime passes a zero-initialized instance of the value type.

反射在调用虚方法时使用动态方法查找。Reflection uses dynamic method lookup when invoking virtual methods. 例如,假设类 B 从类 A 继承,并实现名为 M 的虚拟方法。现在,假设您有一个MethodInfo表示类 a 上的 M 的对象。如果使用Invoke方法在 B 类型的对象上调用 M,则反射将使用由类 b 提供的实现。即使类型 B 的对象强制转换为,也会使用类 B 提供的实现(请参阅下面的代码示例)。For example, suppose that class B inherits from class A and both implement a virtual method named M. Now suppose that you have a MethodInfo object that represents M on class A. If you use the Invoke method to invoke M on an object of type B, then reflection will use the implementation given by class B. Even if the object of type B is cast to A, the implementation given by class B is used (see code sample below).

另一方面,如果方法是非虚拟的,则反射将使用从中获取的MethodInfo类型提供的实现,而不考虑作为目标传递的对象的类型。On the other hand, if the method is non-virtual, then reflection will use the implementation given by the type from which the MethodInfo was obtained, regardless of the type of the object passed as the target.

对于完全受信任的代码,将忽略访问限制。Access restrictions are ignored for fully trusted code. 也就是说,只要代码完全受信任,就可以通过反射访问和调用私有构造函数、方法、字段和属性。That is, private constructors, methods, fields, and properties can be accessed and invoked via reflection whenever the code is fully trusted.

如果调用的方法引发异常, TargetInvocationException.GetException则返回异常。If the invoked method throws an exception, TargetInvocationException.GetException returns the exception. 此实现引发NotSupportedExceptionThis implementation throws a NotSupportedException.

备注

从开始ReflectionPermission ReflectionPermissionFlag.RestrictedMemberAccess ,如果调用方已获得标志并且非公共成员的授予集限制为调用方的授予集或子集,则可以使用此方法访问非公共成员。 .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1缺少.Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (请参阅反射的安全注意事项。)(See Security Considerations for Reflection.)

若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
当通过诸如InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])等机制后期绑定调用时。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). 关联的枚举:MemberAccessAssociated enumeration: MemberAccess.

另请参阅

适用于