Type.InvokeMember Type.InvokeMember Type.InvokeMember Method

定义

调用当前 Type 的特定成员。Invokes a specific member of the current Type.

重载

InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])

当在派生类中重写时,使用指定的绑定约束并匹配指定的参数列表、修饰符和区域性,调用指定成员。When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture.

InvokeMember(String, BindingFlags, Binder, Object, Object[]) InvokeMember(String, BindingFlags, Binder, Object, Object[]) InvokeMember(String, BindingFlags, Binder, Object, Object[])

使用指定的绑定约束并匹配指定的参数列表,调用指定成员。Invokes the specified member, using the specified binding constraints and matching the specified argument list.

InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo) InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo) InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo)

使用指定的绑定约束和匹配的指定参数列表及区域性来调用指定成员。Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.

InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])

当在派生类中重写时,使用指定的绑定约束并匹配指定的参数列表、修饰符和区域性,调用指定成员。When overridden in a derived class, invokes the specified member, using the specified binding constraints and matching the specified argument list, modifiers and culture.

public:
 abstract System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args, cli::array <System::Reflection::ParameterModifier> ^ modifiers, System::Globalization::CultureInfo ^ culture, cli::array <System::String ^> ^ namedParameters);
public abstract object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters);
abstract member InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Reflection.ParameterModifier[] * System.Globalization.CultureInfo * string[] -> obj

参数

name
String String String

字符串,它包含要调用的构造函数、方法、属性或字段成员的名称。The string containing the name of the constructor, method, property, or field member to invoke.

- 或 --or- 空字符串 (""),表示调用默认成员。An empty string ("") to invoke the default member.

- 或 --or- 对于 IDispatch 成员,则为一个表示 DispID 的字符串,例如"[DispID=3]"。For IDispatch members, a string representing the DispID, for example "[DispID=3]".

invokeAttr
BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted. 访问可以是 BindingFlags 之一,如 PublicNonPublicPrivateInvokeMethodGetField 等。The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. 查找类型无需指定。The type of lookup need not be specified. 如果省略查找的类型,则将使用 BindingFlags.Public | BindingFlags.Instance | BindingFlags.StaticIf the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static are used.

binder
Binder Binder Binder

一个对象,该对象定义一组属性并启用绑定,而绑定可能涉及选择重载方法、强制参数类型和通过反射调用成员。An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

- 或 --or- 要使用 DefaultBinder 的空引用(在 Visual Basic 中为 Nothing)。A null reference (Nothing in Visual Basic), to use the DefaultBinder. 请注意,为了成功地使用变量参数来调用方法重载,可能必须显式定义 Binder 对象。Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.

target
Object Object Object

对其调用指定成员的对象。The object on which to invoke the specified member.

args
Object[]

包含传递给要调用的成员的参数的数组。An array containing the arguments to pass to the member to invoke.

modifiers
ParameterModifier[]

ParameterModifier 对象的数组,表示与 args 数组中的相应元素关联的特性。An array of ParameterModifier objects representing the attributes associated with the corresponding element in the args array. 参数的关联的属性存储在成员的签名中。A parameter's associated attributes are stored in the member's signature.

只有在调用 COM 组件时,默认联编程序才处理此参数。The default binder processes this parameter only when calling a COM component.

culture
CultureInfo CultureInfo CultureInfo

表示要使用的全局化区域设置的 CultureInfo 对象,它对区域设置特定的转换可能是必需的,比如将数字 String 转换为 Double。The CultureInfo object representing the globalization locale to use, which may be necessary for locale-specific conversions, such as converting a numeric String to a Double.

- 或 --or- 要使用当前线程的 Nothing 的空引用(在 Visual Basic 中为 CultureInfo)。A null reference (Nothing in Visual Basic) to use the current thread's CultureInfo.

namedParameters
String[]

包含参数名称的数组,args 数组中的值将传递给这些参数。An array containing the names of the parameters to which the values in the args array are passed.

返回

一个对象,表示被调用成员的返回值。An object representing the return value of the invoked member.

实现

异常

invokeAttr 不包含 CreateInstance,并且 namenullinvokeAttr does not contain CreateInstance and name is null.

argsmodifiers 的长度不相同。args and modifiers do not have the same length.

- 或 --or- invokeAttr 不是有效的 BindingFlags 属性。invokeAttr is not a valid BindingFlags attribute.

- 或 --or- invokeAttr 不包含以下某个绑定标志:InvokeMethodCreateInstanceGetFieldSetFieldGetPropertySetPropertyinvokeAttr does not contain one of the following binding flags: InvokeMethod, CreateInstance, GetField, SetField, GetProperty, or SetProperty.

- 或 --or- invokeAttr 包含 CreateInstanceInvokeMethodGetFieldSetFieldGetPropertySetProperty 的组合。invokeAttr contains CreateInstance combined with InvokeMethod, GetField, SetField, GetProperty, or SetProperty.

- 或 --or- invokeAttr 同时包含 GetFieldSetFieldinvokeAttr contains both GetField and SetField.

- 或 --or- invokeAttr 同时包含 GetPropertySetPropertyinvokeAttr contains both GetProperty and SetProperty.

- 或 --or- invokeAttr 包含 InvokeMethodSetFieldSetProperty 的组合。invokeAttr contains InvokeMethod combined with SetField or SetProperty.

- 或 --or- invokeAttr 包含 SetField,并且 args 具有多个元素。invokeAttr contains SetField and args has more than one element.

- 或 --or- 命名的参数数组大于参数数组。The named parameter array is larger than the argument array.

- 或 --or- 对 COM 对象调用了此方法,但以下绑定标志中有一个未传入:BindingFlags.InvokeMethodBindingFlags.GetPropertyBindingFlags.SetPropertyBindingFlags.PutDispPropertyBindingFlags.PutRefDispPropertyThis method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod, BindingFlags.GetProperty, BindingFlags.SetProperty, BindingFlags.PutDispProperty, or BindingFlags.PutRefDispProperty.

- 或 --or- 其中一个命名参数数组包含一个值为 null 的字符串。One of the named parameter arrays contains a string that is null.

指定的成员是类初始值设定项。The specified member is a class initializer.

找不到此字段或属性。The field or property cannot be found.

找不到与 args 中的参数匹配的方法。No method can be found that matches the arguments in args.

- 或 --or- 找不到具有 namedParameters 中提供的参数名称的成员。No member can be found that has the argument names supplied in namedParameters.

- 或 --or- 当前 Type 对象表示包含开放类型参数的类型,也就是说,ContainsGenericParameters 将返回 trueThe current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true.

不能在 target 上调用指定的成员。The specified member cannot be invoked on target.

多个方法与绑定条件匹配。More than one method matches the binding criteria.

name 表示的方法具有一个或多个未指定的泛型类型参数。The method represented by name has one or more unspecified generic type parameters. 也就是说,此方法的 ContainsGenericParameters 属性将返回 trueThat is, the method's ContainsGenericParameters property returns true.

注解

InvokeMember 调用构造函数成员或方法成员,获取或设置的属性成员,获取或设置数据字段成员,或获取或设置数组成员的元素。InvokeMember calls a constructor member or a method member, gets or sets a property member, gets or sets a data field member, or gets or sets an element of an array member.

备注

不能使用InvokeMember调用泛型方法。You cannot use InvokeMember to invoke a generic method.

当调用IDispatch成员可以指定而不是成员名称,使用字符串格式的 DispID"[DispID = # #]"。When you invoke an IDispatch member you can specify the DispID instead of the member name, using the string format "[DispID=##]". 例如,如果 DispID MyComMethod 为 3,则可以指定字符串"[DispID = 3]"而不是"MyComMethod"。For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". 调用成员的 DispID 速度比按名称查找该成员。Invoking a member by DispID is faster than looking up the member by name. 在复杂的聚合方案中,DispID 有时是调用所需的成员的唯一方法。In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.

尽管默认联编程序不会处理ParameterModifierCultureInfo(modifiersculture参数),您可以使用抽象System.Reflection.Binder类编写的自定义联编程序modifiersculture.Although the default binder does not process ParameterModifier or CultureInfo (the modifiers and culture parameters), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers and culture. ParameterModifier 通过 COM 互操作调用时,才使用和处理由引用传递的参数。ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

namedParameters 数组中的每个参数对应 args 数组中的元素来获取值。Each parameter in the namedParameters array gets the value in the corresponding element in the args array. 如果 args 的长度大于 namedParameters 的长度,则剩余的自变量值将按顺序传递。If the length of args is greater than the length of namedParameters, the remaining argument values are passed in order.

namedParameters数组可用于更改输入数组中参数的顺序。The namedParameters array can be used to change the order of arguments in an input array. 例如,对于给定的方法M(string a, int b)(M(ByVal a As String, ByVal b As Integer)在 Visual Basic 中) 和输入的数组{ 42, "x" },输入的数组可以传递不变以args如果数组{ "b", "a" }为提供namedParametersFor example, given the method M(string a, int b) (M(ByVal a As String, ByVal b As Integer) in Visual Basic) and the input array { 42, "x" }, the input array can be passed unchanged to args if the array { "b", "a" } is supplied for namedParameters.

以下BindingFlags的筛选器标志可以用于定义要在搜索中包括的成员:The following BindingFlags filter flags can be used to define which members to include in the search:

  • 指定BindingFlags.Public若要在搜索中包括公共成员。Specify BindingFlags.Public to include public members in the search.

  • 指定BindingFlags.NonPublic若要在搜索中包括非公共成员 (即私有、 内部和受保护成员)。Specify BindingFlags.NonPublic to include non-public members (that is, private, internal, and protected members) in the search.

  • 指定BindingFlags.FlattenHierarchy包括层次结构中的静态成员。Specify BindingFlags.FlattenHierarchy to include static members up the hierarchy.

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase 若要忽略大小写的nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly 若要搜索仅在声明的成员Type,不只是继承的成员。BindingFlags.DeclaredOnly to search only the members declared on the Type, not members that were simply inherited.

以下BindingFlags调用标志可以用于表示要与该成员执行的操作:The following BindingFlags invocation flags can be used to denote what action to take with the member:

  • CreateInstance 若要调用构造函数。CreateInstance to invoke a constructor. name 将被忽略。name is ignored. 与其他调用标志无效。Not valid with other invocation flags.

  • InvokeMethod 若要调用一个方法,但不是构造函数或类型初始值设定项。InvokeMethod to invoke a method, but not a constructor or a type initializer. 不有效,且SetFieldSetPropertyNot valid with SetField or SetProperty. 如果InvokeMethod其本身而言,指定BindingFlags.PublicBindingFlags.Instance,和BindingFlags.Static自动包括在内。If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included.

  • GetField 若要获取字段的值。GetField to get the value of a field. 使用无效SetFieldNot valid with SetField.

  • SetField 若要设置字段的值。SetField to set the value of a field. 使用无效GetFieldNot valid with GetField.

  • GetProperty 若要获取的属性。GetProperty to get a property. 使用无效SetPropertyNot valid with SetProperty.

  • SetProperty 若要设置的属性。SetProperty to set a property. 使用无效GetPropertyNot valid with GetProperty.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

如果下列条件都成立,则将调用一个方法:A method will be invoked if both of the following conditions are true:

  • 方法声明中的参数数量等于的中的参数数目args数组 (除非该成员上定义了默认参数和BindingFlags.OptionalParamBinding指定)。The number of parameters in the method declaration equals the number of arguments in the args array (unless default arguments are defined on the member and BindingFlags.OptionalParamBinding is specified).

  • 每个自变量的类型可以转换为参数的类型绑定器。The type of each argument can be converted by the binder to the type of the parameter.

联编程序将查找所有匹配的方法。The binder will find all of the matching methods. 这些方法会找到基于请求的绑定类型 (BindingFlagsInvokeMethodGetProperty,依此类推)。These methods are found based upon the type of binding requested (BindingFlags values InvokeMethod, GetProperty, and so on). 按名称、 数量的参数,并搜索修饰符联编程序中定义的一组筛选的组的方法。The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.

选择该方法后,调用此操作。After the method is selected, it is invoked. 此时,检查可访问性。Accessibility is checked at that point. 搜索可能基于与方法关联的可访问性属性来控制搜索的组的方法。The search may control which set of methods are searched based upon the accessibility attribute associated with the method. Binder.BindToMethod方法的Binder类负责选择要调用的方法。The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. 默认联编程序选择最精确的匹配。The default binder selects the most specific match.

InvokeMember 可以使用调用参数具有默认值的方法。InvokeMember can be used to invoke methods with parameters that have default values. 若要将绑定到这些方法,反射需要BindingFlags.OptionalParamBinding来指定。To bind to these methods, Reflection requires BindingFlags.OptionalParamBinding to be specified. 对于具有默认值的参数,可以提供不同的值,也可以提供Missing.Value可以使用默认值。For a parameter that has a default value, you can either supply a different value, or supply Missing.Value to use the default value.

例如,考虑 MyMethod 之类的方法 (int,x、 float y = 2.0)。For example, consider a method such as MyMethod(int x, float y = 2.0). 若要调用此方法仅为 mymethod (4) 的第一个参数,传递上面的绑定标志之一并传递两个参数,即第一个参数 4 和Missing.Value的第二个参数。To invoke this method with only the first argument as MyMethod(4), pass one of the above binding flags and pass two arguments, namely, 4 for the first argument and Missing.Value for the second argument. 除非使用Missing.Value,否则不能省略可选参数与Invoke方法。Unless you use Missing.Value, you may not omit optional parameters with the Invoke method. 如果必须这样做,使用InvokeMember相反。If you must do so, use InvokeMember instead.

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

可以使用Type.InvokeMember若要将字段设置为特定值,通过指定BindingFlags.SetFieldYou can use Type.InvokeMember to set a field to a particular value by specifying BindingFlags.SetField. 例如,如果你想要设置 C 和 F 的类上名为 F 的公共实例字段是String,您可以使用如下代码:For example, if you want to set a public instance field named F on class C, and F is a String, you can use code such as:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {"strings new value"}, null, null, null);

如果 F String[],您可以使用如下代码:If F is a String[], you can use code such as:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {new String[]{"a","z","c","d"}}, null, null, null);

这将初始化字段 F 到此新的数组。which will initialize the field F to this new array. 此外可以使用Type.InvokeMember设置通过使用如下所示的代码提供的值,然后选择下一步值索引数组中的位置:You can also use Type.InvokeMember to set a position in an array by supplying the index of the value and then the next value by using code such as the following:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {1, "b"}, null, null, null);

这将更改 F 包含字符串"b"数组中的字符串"z"。This will change string "z" in the array that F holds to string "b".

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,可以使用此方法访问非公共成员,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标记线程和非公共成员的授予集限制到调用方的授予集或子集其中。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
用于访问非公共成员,而不考虑其授予集。for accessing non-public members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

SecurityPermission
若要调用非托管的代码。to call unmanaged code. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

另请参阅

InvokeMember(String, BindingFlags, Binder, Object, Object[]) InvokeMember(String, BindingFlags, Binder, Object, Object[]) InvokeMember(String, BindingFlags, Binder, Object, Object[])

使用指定的绑定约束并匹配指定的参数列表,调用指定成员。Invokes the specified member, using the specified binding constraints and matching the specified argument list.

public:
 virtual System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args);
abstract member InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] -> obj
override this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] -> obj

参数

name
String String String

字符串,它包含要调用的构造函数、方法、属性或字段成员的名称。The string containing the name of the constructor, method, property, or field member to invoke.

- 或 --or- 空字符串 (""),表示调用默认成员。An empty string ("") to invoke the default member.

- 或 --or- 对于 IDispatch 成员,则为一个表示 DispID 的字符串,例如"[DispID=3]"。For IDispatch members, a string representing the DispID, for example "[DispID=3]".

invokeAttr
BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted. 访问可以是 BindingFlags 之一,如 PublicNonPublicPrivateInvokeMethodGetField 等。The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. 查找类型无需指定。The type of lookup need not be specified. 如果省略查找的类型,则将使用 BindingFlags.Public | BindingFlags.Instance | BindingFlags.StaticIf the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static are used.

binder
Binder Binder Binder

一个对象,该对象定义一组属性并启用绑定,而绑定可能涉及选择重载方法、强制参数类型和通过反射调用成员。An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

- 或 --or- 要使用 Nothing 的空引用(在 Visual Basic 中为 DefaultBinder)。A null reference (Nothing in Visual Basic), to use the DefaultBinder. 请注意,为了成功地使用变量参数来调用方法重载,可能必须显式定义 Binder 对象。Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.

target
Object Object Object

对其调用指定成员的对象。The object on which to invoke the specified member.

args
Object[]

包含传递给要调用的成员的参数的数组。An array containing the arguments to pass to the member to invoke.

返回

一个对象,表示被调用成员的返回值。An object representing the return value of the invoked member.

实现

异常

invokeAttr 不包含 CreateInstance,并且 namenullinvokeAttr does not contain CreateInstance and name is null.

invokeAttr 不是有效的 BindingFlags 属性。invokeAttr is not a valid BindingFlags attribute.

- 或 --or- invokeAttr 不包含以下某个绑定标志:InvokeMethodCreateInstanceGetFieldSetFieldGetPropertySetPropertyinvokeAttr does not contain one of the following binding flags: InvokeMethod, CreateInstance, GetField, SetField, GetProperty, or SetProperty.

- 或 --or- invokeAttr 包含 CreateInstanceInvokeMethodGetFieldSetFieldGetPropertySetProperty 的组合。invokeAttr contains CreateInstance combined with InvokeMethod, GetField, SetField, GetProperty, or SetProperty.

- 或 --or- invokeAttr 同时包含 GetFieldSetFieldinvokeAttr contains both GetField and SetField.

- 或 --or- invokeAttr 同时包含 GetPropertySetPropertyinvokeAttr contains both GetProperty and SetProperty.

- 或 --or- invokeAttr 包含 InvokeMethodSetFieldSetProperty 的组合。invokeAttr contains InvokeMethod combined with SetField or SetProperty.

- 或 --or- invokeAttr 包含 SetField,并且 args 具有多个元素。invokeAttr contains SetField and args has more than one element.

- 或 --or- 对 COM 对象调用了此方法,但以下绑定标志中有一个未传入:BindingFlags.InvokeMethodBindingFlags.GetPropertyBindingFlags.SetPropertyBindingFlags.PutDispPropertyBindingFlags.PutRefDispPropertyThis method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod, BindingFlags.GetProperty, BindingFlags.SetProperty, BindingFlags.PutDispProperty, or BindingFlags.PutRefDispProperty.

- 或 --or- 其中一个命名参数数组包含一个值为 null 的字符串。One of the named parameter arrays contains a string that is null.

指定的成员是类初始值设定项。The specified member is a class initializer.

找不到此字段或属性。The field or property cannot be found.

找不到与 args 中的参数匹配的方法。No method can be found that matches the arguments in args.

- 或 --or- 当前 Type 对象表示包含开放类型参数的类型,也就是说,ContainsGenericParameters 将返回 trueThe current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true.

不能在 target 上调用指定的成员。The specified member cannot be invoked on target.

多个方法与绑定条件匹配。More than one method matches the binding criteria.

.NET Compact Framework 当前不支持此方法。The .NET Compact Framework does not currently support this method.

name 表示的方法具有一个或多个未指定的泛型类型参数。The method represented by name has one or more unspecified generic type parameters. 也就是说,此方法的 ContainsGenericParameters 属性将返回 trueThat is, the method's ContainsGenericParameters property returns true.

示例

下面的示例使用InvokeMember访问成员的类型。The following example uses InvokeMember to access members of a type.

using namespace System;
using namespace System::Reflection;

// This sample class has a field, constructor, method, and property.
ref class MyType
{
private:
   Int32 myField;

public:
   MyType( interior_ptr<Int32> x )
   {
       *x *= 5;
   }

   virtual String^ ToString() override
   {
      return myField.ToString();
   }

   property Int32 MyProp 
   {
      Int32 get()
      {
         return myField;
      }

      void set( Int32 value )
      {
         if ( value < 1 )
                  throw gcnew ArgumentOutOfRangeException( "value",value,"value must be > 0" );

         myField = value;
      }
   }
};

int main()
{
   Type^ t = MyType::typeid;

   // Create an instance of a type.
   array<Object^>^args = {8};
   Console::WriteLine( "The value of x before the constructor is called is {0}.", args[ 0 ] );
   Object^ obj = t->InvokeMember( nullptr, static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::CreateInstance), nullptr, nullptr, args );
   Console::WriteLine( "Type: {0}", obj->GetType() );
   Console::WriteLine( "The value of x after the constructor returns is {0}.", args[ 0 ] );

   // Read and write to a field.
   array<Object^>^obj5 = {5};
   t->InvokeMember( "myField", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::SetField), nullptr, obj, obj5 );
   Int32 v = safe_cast<Int32>(t->InvokeMember( "myField", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::GetField), nullptr, obj, nullptr ));
   Console::WriteLine( "myField: {0}", v );

   // Call a method.
   String^ s = safe_cast<String^>(t->InvokeMember( "ToString", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::InvokeMethod), nullptr, obj, nullptr ));
   Console::WriteLine( "ToString: {0}", s );

   // Read and write a property. First, attempt to assign an
   // invalid value; then assign a valid value; finally, get
   // the value.
   try
   {
      // Assign the value zero to MyProp. The Property Set 
      // throws an exception, because zero is an invalid value.
      // InvokeMember catches the exception, and throws 
      // TargetInvocationException. To discover the real cause
      // you must catch TargetInvocationException and examine
      // the inner exception. 
      array<Object^>^obj0 = {(int^)0};
      t->InvokeMember( "MyProp", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::SetProperty), nullptr, obj, obj0 );
   }
   catch ( TargetInvocationException^ e ) 
   {
      // If the property assignment failed for some unexpected
      // reason, rethrow the TargetInvocationException.
      if ( e->InnerException->GetType() != ArgumentOutOfRangeException::typeid )
            throw;

      Console::WriteLine( "An invalid value was assigned to MyProp." );
   }

   array<Object^>^obj2 = {2};
   t->InvokeMember( "MyProp", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::SetProperty), nullptr, obj, obj2 );
   v =  safe_cast<Int32>(t->InvokeMember( "MyProp", static_cast<BindingFlags>(BindingFlags::DeclaredOnly | BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance | BindingFlags::GetProperty), nullptr, obj, nullptr ));
   Console::WriteLine( "MyProp: {0}", v );
}
using System;
using System.Reflection;

// This sample class has a field, constructor, method, and property.
class MyType 
{
    Int32 myField;
    public MyType(ref Int32 x) {x *= 5;}
    public override String ToString() {return myField.ToString();}
    public Int32 MyProp 
    {
        get {return myField;}
        set 
        { 
            if (value < 1) 
                throw new ArgumentOutOfRangeException("value", value, "value must be > 0");
            myField = value;
        }
    }
}

class MyApp 
{
    static void Main() 
    {
        Type t = typeof(MyType);
        // Create an instance of a type.
        Object[] args = new Object[] {8};
        Console.WriteLine("The value of x before the constructor is called is {0}.", args[0]);
        Object obj = t.InvokeMember(null, 
            BindingFlags.DeclaredOnly | 
            BindingFlags.Public | BindingFlags.NonPublic | 
            BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
        Console.WriteLine("Type: " + obj.GetType().ToString());
        Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]);

        // Read and write to a field.
        t.InvokeMember("myField", 
            BindingFlags.DeclaredOnly | 
            BindingFlags.Public | BindingFlags.NonPublic | 
            BindingFlags.Instance | BindingFlags.SetField, null, obj, new Object[] {5});
        Int32 v = (Int32) t.InvokeMember("myField", 
            BindingFlags.DeclaredOnly | 
            BindingFlags.Public | BindingFlags.NonPublic | 
            BindingFlags.Instance | BindingFlags.GetField, null, obj, null);
        Console.WriteLine("myField: " + v);

        // Call a method.
        String s = (String) t.InvokeMember("ToString", 
            BindingFlags.DeclaredOnly | 
            BindingFlags.Public | BindingFlags.NonPublic | 
            BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);
        Console.WriteLine("ToString: " + s);

        // Read and write a property. First, attempt to assign an
        // invalid value; then assign a valid value; finally, get
        // the value.
        try 
        {
            // Assign the value zero to MyProp. The Property Set 
            // throws an exception, because zero is an invalid value.
            // InvokeMember catches the exception, and throws 
            // TargetInvocationException. To discover the real cause
            // you must catch TargetInvocationException and examine
            // the inner exception. 
            t.InvokeMember("MyProp", 
                BindingFlags.DeclaredOnly | 
                BindingFlags.Public | BindingFlags.NonPublic | 
                BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {0});
        } 
        catch (TargetInvocationException e) 
        {
            // If the property assignment failed for some unexpected
            // reason, rethrow the TargetInvocationException.
            if (e.InnerException.GetType() != 
                typeof(ArgumentOutOfRangeException)) 
                throw;
            Console.WriteLine("An invalid value was assigned to MyProp.");
        }
        t.InvokeMember("MyProp", 
            BindingFlags.DeclaredOnly | 
            BindingFlags.Public | BindingFlags.NonPublic | 
            BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {2});
        v = (Int32) t.InvokeMember("MyProp", 
            BindingFlags.DeclaredOnly | 
            BindingFlags.Public | BindingFlags.NonPublic | 
            BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null);
        Console.WriteLine("MyProp: " + v);
    }
}
Imports System
Imports System.Reflection

' This sample class has a field, constructor, method, and property.
Class MyType
    Private myField As Int32

    Public Sub New(ByRef x As Int32)
        x *= 5
    End Sub 'New

    Public Overrides Function ToString() As [String]
        Return myField.ToString()
    End Function 'ToString

    Public Property MyProp() As Int32
        Get
            Return myField
        End Get
        Set(ByVal Value As Int32)
            If Value < 1 Then
                Throw New ArgumentOutOfRangeException("value", Value, "value must be > 0")
            End If
            myField = Value
        End Set
    End Property
End Class 'MyType

Class MyApp

    Shared Sub Main()
        Dim t As Type = GetType(MyType)
        ' Create an instance of a type.
        Dim args() As [Object] = {8}
        Console.WriteLine("The value of x before the constructor is called is {0}.", args(0))
        Dim obj As [Object] = t.InvokeMember(Nothing, BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.CreateInstance, Nothing, Nothing, args)
        Console.WriteLine("Type: {0}", obj.GetType().ToString())
        Console.WriteLine("The value of x after the constructor returns is {0}.", args(0))

        ' Read and write to a field.
        t.InvokeMember("myField", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.SetField, Nothing, obj, New [Object]() {5})
        Dim v As Int32 = CType(t.InvokeMember("myField", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, obj, Nothing), Int32)
        Console.WriteLine("myField: {0}", v)

        ' Call a method.
        Dim s As [String] = CType(t.InvokeMember("ToString", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, obj, Nothing), [String])
        Console.WriteLine("ToString: {0}", s)

        ' Read and write a property. First, attempt to assign an
        ' invalid value; then assign a valid value; finally, get
        ' the value.
        Try
            ' Assign the value zero to MyProp. The Property Set 
            ' throws an exception, because zero is an invalid value.
            ' InvokeMember catches the exception, and throws 
            ' TargetInvocationException. To discover the real cause
            ' you must catch TargetInvocationException and examine
            ' the inner exception. 
            t.InvokeMember("MyProp", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.SetProperty, Nothing, obj, New [Object]() {0})
        Catch e As TargetInvocationException
            ' If the property assignment failed for some unexpected
            ' reason, rethrow the TargetInvocationException.
            If Not e.InnerException.GetType() Is GetType(ArgumentOutOfRangeException) Then
                Throw
            End If
            Console.WriteLine("An invalid value was assigned to MyProp.")
        End Try
        t.InvokeMember("MyProp", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.SetProperty, Nothing, obj, New [Object]() {2})
        v = CType(t.InvokeMember("MyProp", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetProperty, Nothing, obj, Nothing), Int32)
        Console.WriteLine("MyProp: {0}", v)
    End Sub 'Main
End Class 'MyApp

注解

备注

不能使用InvokeMember调用泛型方法。You cannot use InvokeMember to invoke a generic method.

以下BindingFlags的筛选器标志可以用于定义要在搜索中包括的成员:The following BindingFlags filter flags can be used to define which members to include in the search:

  • 指定BindingFlags.Public若要在搜索中包括公共成员。Specify BindingFlags.Public to include public members in the search.

  • 指定BindingFlags.NonPublic若要在搜索中包括非公共成员 (即,专用和受保护成员)。Specify BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.

  • 指定BindingFlags.FlattenHierarchy包括层次结构中的静态成员。Specify BindingFlags.FlattenHierarchy to include static members up the hierarchy.

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase 若要忽略大小写的nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly 若要搜索仅在声明的成员Type,不只是继承的成员。BindingFlags.DeclaredOnly to search only the members declared on the Type, not members that were simply inherited.

以下BindingFlags调用标志可以用于表示要与该成员执行的操作:The following BindingFlags invocation flags can be used to denote what action to take with the member:

  • CreateInstance 若要调用构造函数。CreateInstance to invoke a constructor. name 将被忽略。name is ignored. 与其他调用标志无效。Not valid with other invocation flags.

  • InvokeMethod 若要调用一个方法,但不是构造函数或类型初始值设定项。InvokeMethod to invoke a method, but not a constructor or a type initializer. 不有效,且SetFieldSetPropertyNot valid with SetField or SetProperty. 如果InvokeMethod其本身而言,指定BindingFlags.PublicBindingFlags.Instance,和BindingFlags.Static自动包括在内。If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included.

  • GetField 若要获取字段的值。GetField to get the value of a field. 使用无效SetFieldNot valid with SetField.

  • SetField 若要设置字段的值。SetField to set the value of a field. 使用无效GetFieldNot valid with GetField.

  • GetProperty 若要获取的属性。GetProperty to get a property. 使用无效SetPropertyNot valid with SetProperty.

  • SetProperty 若要设置的属性。SetProperty to set a property. 使用无效GetPropertyNot valid with GetProperty.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

如果下列条件都成立,则将调用一个方法:A method will be invoked if both of the following conditions are true:

  • 方法声明中的参数数量等于的中的参数数目args数组 (除非该成员上定义了默认参数和BindingFlags.OptionalParamBinding指定)。The number of parameters in the method declaration equals the number of arguments in the args array (unless default arguments are defined on the member and BindingFlags.OptionalParamBinding is specified).

  • 每个自变量的类型可以转换为参数的类型绑定器。The type of each argument can be converted by the binder to the type of the parameter.

联编程序将查找所有匹配的方法。The binder will find all of the matching methods. 这些方法会找到基于请求的绑定类型 (BindingFlagsInvokeMethodGetProperty,依此类推)。These methods are found based upon the type of binding requested (BindingFlags values InvokeMethod, GetProperty, and so on). 按名称、 数量的参数,并搜索修饰符联编程序中定义的一组筛选的组的方法。The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.

选择该方法后,调用此操作。After the method is selected, it is invoked. 此时,检查可访问性。Accessibility is checked at that point. 搜索可能基于与方法关联的可访问性属性来控制搜索的组的方法。The search may control which set of methods are searched based upon the accessibility attribute associated with the method. Binder.BindToMethod方法的Binder类负责选择要调用的方法。The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. 默认联编程序选择最精确的匹配。The default binder selects the most specific match.

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

可以使用Type.InvokeMember若要将字段设置为特定值,通过指定BindingFlags.SetFieldYou can use Type.InvokeMember to set a field to a particular value by specifying BindingFlags.SetField. 例如,如果你想要设置 C 和 F 的类上名为 F 的公共实例字段是String,您可以使用如下代码:For example, if you want to set a public instance field named F on class C, and F is a String, you can use code such as:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {"strings new value"});

如果 F String[],您可以使用如下代码:If F is a String[], you can use code such as:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {new String[]{"a","z","c","d"}});

这将初始化字段 F 到此新的数组。which will initialize the field F to this new array. 此外可以使用Type.InvokeMember设置通过使用如下所示的代码提供的值,然后选择下一步值索引数组中的位置:You can also use Type.InvokeMember to set a position in an array by supplying the index of the value and then the next value by using code such as the following:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {1, "b"});

这将更改 F 包含字符串"b"数组中的字符串"z"。This will change string "z" in the array that F holds to string "b".

当调用IDispatch成员,您可以指定而不是成员名称,使用字符串格式的 DispID"[DispID = # #]"。When you invoke an IDispatch member, you can specify the DispID instead of the member name, using the string format "[DispID=##]". 例如,如果 DispID MyComMethod 为 3,则可以指定字符串"[DispID = 3]"而不是"MyComMethod"。For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". 调用成员的 DispID 速度比按名称查找该成员。Invoking a member by DispID is faster than looking up the member by name. 在复杂的聚合方案中,DispID 有时是调用所需的成员的唯一方法。In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,可以使用此方法访问非公共成员,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标记线程和非公共成员的授予集限制到调用方的授予集或子集其中。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
用于访问非公共成员,而不考虑其授予集。for accessing non-public members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

SecurityPermission
若要调用非托管的代码。to call unmanaged code. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

另请参阅

InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo) InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo) InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo)

使用指定的绑定约束和匹配的指定参数列表及区域性来调用指定成员。Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.

public:
 virtual System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Globalization.CultureInfo culture);
abstract member InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Globalization.CultureInfo -> obj
override this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Globalization.CultureInfo -> obj

参数

name
String String String

字符串,它包含要调用的构造函数、方法、属性或字段成员的名称。The string containing the name of the constructor, method, property, or field member to invoke.

- 或 --or- 空字符串 (""),表示调用默认成员。An empty string ("") to invoke the default member.

- 或 --or- 对于 IDispatch 成员,则为一个表示 DispID 的字符串,例如"[DispID=3]"。For IDispatch members, a string representing the DispID, for example "[DispID=3]".

invokeAttr
BindingFlags BindingFlags BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。A bitwise combination of the enumeration values that specify how the search is conducted. 访问可以是 BindingFlags 之一,如 PublicNonPublicPrivateInvokeMethodGetField 等。The access can be one of the BindingFlags such as Public, NonPublic, Private, InvokeMethod, GetField, and so on. 查找类型无需指定。The type of lookup need not be specified. 如果省略查找的类型,则将使用 BindingFlags.Public | BindingFlags.Instance | BindingFlags.StaticIf the type of lookup is omitted, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static are used.

binder
Binder Binder Binder

一个对象,该对象定义一组属性并启用绑定,而绑定可能涉及选择重载方法、强制参数类型和通过反射调用成员。An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

- 或 --or- 要使用 Nothing 的空引用(在 Visual Basic 中为 DefaultBinder)。A null reference (Nothing in Visual Basic), to use the DefaultBinder. 请注意,为了成功地使用变量参数来调用方法重载,可能必须显式定义 Binder 对象。Note that explicitly defining a Binder object may be required for successfully invoking method overloads with variable arguments.

target
Object Object Object

对其调用指定成员的对象。The object on which to invoke the specified member.

args
Object[]

包含传递给要调用的成员的参数的数组。An array containing the arguments to pass to the member to invoke.

culture
CultureInfo CultureInfo CultureInfo

表示要使用的全局化区域设置的对象,它对区域设置特定的转换可能是必需的,比如将数字 String 转换为 DoubleThe object representing the globalization locale to use, which may be necessary for locale-specific conversions, such as converting a numeric String to a Double.

- 或 --or- 要使用当前线程的 Nothing 的空引用(在 Visual Basic 中为 CultureInfo)。A null reference (Nothing in Visual Basic) to use the current thread's CultureInfo.

返回

一个对象,表示被调用成员的返回值。An object representing the return value of the invoked member.

实现

异常

invokeAttr 不包含 CreateInstance,并且 namenullinvokeAttr does not contain CreateInstance and name is null.

invokeAttr 不是有效的 BindingFlags 属性。invokeAttr is not a valid BindingFlags attribute.

- 或 --or- invokeAttr 不包含以下某个绑定标志:InvokeMethodCreateInstanceGetFieldSetFieldGetPropertySetPropertyinvokeAttr does not contain one of the following binding flags: InvokeMethod, CreateInstance, GetField, SetField, GetProperty, or SetProperty.

- 或 --or- invokeAttr 包含 CreateInstanceInvokeMethodGetFieldSetFieldGetPropertySetProperty 的组合。invokeAttr contains CreateInstance combined with InvokeMethod, GetField, SetField, GetProperty, or SetProperty.

- 或 --or- invokeAttr 同时包含 GetFieldSetFieldinvokeAttr contains both GetField and SetField.

- 或 --or- invokeAttr 同时包含 GetPropertySetPropertyinvokeAttr contains both GetProperty and SetProperty.

- 或 --or- invokeAttr 包含 InvokeMethodSetFieldSetProperty 的组合。invokeAttr contains InvokeMethod combined with SetField or SetProperty.

- 或 --or- invokeAttr 包含 SetField,并且 args 具有多个元素。invokeAttr contains SetField and args has more than one element.

- 或 --or- 对 COM 对象调用了此方法,但以下绑定标志中有一个未传入:BindingFlags.InvokeMethodBindingFlags.GetPropertyBindingFlags.SetPropertyBindingFlags.PutDispPropertyBindingFlags.PutRefDispPropertyThis method is called on a COM object and one of the following binding flags was not passed in: BindingFlags.InvokeMethod, BindingFlags.GetProperty, BindingFlags.SetProperty, BindingFlags.PutDispProperty, or BindingFlags.PutRefDispProperty.

- 或 --or- 其中一个命名参数数组包含一个值为 null 的字符串。One of the named parameter arrays contains a string that is null.

指定的成员是类初始值设定项。The specified member is a class initializer.

找不到此字段或属性。The field or property cannot be found.

找不到与 args 中的参数匹配的方法。No method can be found that matches the arguments in args.

- 或 --or- 当前 Type 对象表示包含开放类型参数的类型,也就是说,ContainsGenericParameters 将返回 trueThe current Type object represents a type that contains open type parameters, that is, ContainsGenericParameters returns true.

不能在 target 上调用指定的成员。The specified member cannot be invoked on target.

多个方法与绑定条件匹配。More than one method matches the binding criteria.

name 表示的方法具有一个或多个未指定的泛型类型参数。The method represented by name has one or more unspecified generic type parameters. 也就是说,此方法的 ContainsGenericParameters 属性将返回 trueThat is, the method's ContainsGenericParameters property returns true.

注解

尽管默认联编程序不会处理CultureInfo(culture参数),您可以使用抽象System.Reflection.Binder类以编写的自定义联编程序cultureAlthough the default binder does not process CultureInfo (the culture parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process culture.

备注

不能使用InvokeMember调用泛型方法。You cannot use InvokeMember to invoke a generic method.

以下BindingFlags的筛选器标志可以用于定义要在搜索中包括的成员:The following BindingFlags filter flags can be used to define which members to include in the search:

  • 指定BindingFlags.Public若要在搜索中包括公共成员。Specify BindingFlags.Public to include public members in the search.

  • 指定BindingFlags.NonPublic若要在搜索中包括非公共成员 (即私有、 内部和受保护成员)。Specify BindingFlags.NonPublic to include non-public members (that is, private, internal, and protected members) in the search.

  • 指定BindingFlags.FlattenHierarchy包括层次结构中的静态成员。Specify BindingFlags.FlattenHierarchy to include static members up the hierarchy.

以下BindingFlags修饰符标志可以用于更改搜索的工作原理:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase 若要忽略大小写的nameBindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly 若要搜索仅在声明的成员Type,不只是继承的成员。BindingFlags.DeclaredOnly to search only the members declared on the Type, not members that were simply inherited.

以下BindingFlags调用标志可以用于表示要与该成员执行的操作:The following BindingFlags invocation flags can be used to denote what action to take with the member:

  • CreateInstance 若要调用构造函数。CreateInstance to invoke a constructor. name 将被忽略。name is ignored. 与其他调用标志无效。Not valid with other invocation flags.

  • InvokeMethod 若要调用一个方法,但不是构造函数或类型初始值设定项。InvokeMethod to invoke a method, but not a constructor or a type initializer. 不有效,且SetFieldSetPropertyNot valid with SetField or SetProperty. 如果InvokeMethod其本身而言,指定BindingFlags.PublicBindingFlags.Instance,和BindingFlags.Static自动包括在内。If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included.

  • GetField 若要获取字段的值。GetField to get the value of a field. 使用无效SetFieldNot valid with SetField.

  • SetField 若要设置字段的值。SetField to set the value of a field. 使用无效GetFieldNot valid with GetField.

  • GetProperty 若要获取的属性。GetProperty to get a property. 使用无效SetPropertyNot valid with SetProperty.

  • SetProperty 若要设置的属性。SetProperty to set a property. 使用无效GetPropertyNot valid with GetProperty.

有关更多信息,请参见System.Reflection.BindingFlagsSee System.Reflection.BindingFlags for more information.

如果下列条件都成立,则将调用一个方法:A method will be invoked if both of the following conditions are true:

  • 方法声明中的参数数量等于的中的参数数目args数组 (除非该成员上定义了默认参数和BindingFlags.OptionalParamBinding指定)。The number of parameters in the method declaration equals the number of arguments in the args array (unless default arguments are defined on the member and BindingFlags.OptionalParamBinding is specified).

  • 每个自变量的类型可以转换为参数的类型绑定器。The type of each argument can be converted by the binder to the type of the parameter.

联编程序将查找所有匹配的方法。The binder will find all of the matching methods. 这些方法会找到基于请求的绑定类型 (BindingFlagsInvokeMethodGetProperty,依此类推)。These methods are found based upon the type of binding requested (BindingFlags values InvokeMethod, GetProperty, and so on). 按名称、 数量的参数,并搜索修饰符联编程序中定义的一组筛选的组的方法。The set of methods is filtered by the name, number of arguments, and a set of search modifiers defined in the binder.

选择该方法后,调用此操作。After the method is selected, it is invoked. 此时,检查可访问性。Accessibility is checked at that point. 搜索可能基于与方法关联的可访问性属性来控制搜索的组的方法。The search may control which set of methods are searched based upon the accessibility attribute associated with the method. Binder.BindToMethod方法的Binder类负责选择要调用的方法。The Binder.BindToMethod method of the Binder class is responsible for selecting the method to be invoked. 默认联编程序选择最精确的匹配。The default binder selects the most specific match.

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

可以使用Type.InvokeMember若要将字段设置为特定值,通过指定BindingFlags.SetFieldYou can use Type.InvokeMember to set a field to a particular value by specifying BindingFlags.SetField. 例如,如果你想要设置 C 和 F 的类上名为 F 的公共实例字段是String您可以使用如下代码:For example, if you want to set a public instance field named F on class C, and F is a String you can use code such as:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {"strings new value"}, null);

如果 F String[],您可以使用如下代码:If F is a String[], you can use code such as:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {new String[]{"a","z","c","d"}}, null);

这将初始化字段 F 到此新的数组。which will initialize the field F to this new array. 此外可以使用Type.InvokeMember设置通过使用如下所示的代码提供的值,然后选择下一步值索引数组中的位置:You can also use Type.InvokeMember to set a position in an array by supplying the index of the value and then the next value by using code such as the following:

typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {1, "b"}, null);

这将更改 F 包含字符串"b"数组中的字符串"z"。This will change string "z" in the array that F holds to string "b".

当调用IDispatch成员可以指定而不是成员名称,使用字符串格式的 DispID"[DispID = # #]"。When you invoke an IDispatch member you can specify the DispID instead of the member name, using the string format "[DispID=##]". 例如,如果 DispID MyComMethod 为 3,则可以指定字符串"[DispID = 3]"而不是"MyComMethod"。For example, if the DispID of MyComMethod is 3, you can specify the string "[DispID=3]" instead of "MyComMethod". 调用成员的 DispID 速度比按名称查找该成员。Invoking a member by DispID is faster than looking up the member by name. 在复杂的聚合方案中,DispID 有时是调用所需的成员的唯一方法。In complex aggregation scenarios, the DispID is sometimes the only way to invoke the desired member.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,可以使用此方法访问非公共成员,如果授予调用方ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标记线程和非公共成员的授予集限制到调用方的授予集或子集其中。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
用于访问非公共成员,而不考虑其授予集。for accessing non-public members regardless of their grant set. 关联的枚举: MemberAccessAssociated enumeration: MemberAccess

SecurityPermission
若要调用非托管的代码。to call unmanaged code. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

另请参阅

适用于