Type.InvokeMember 方法

定義

叫用目前 Type 的特定成員。Invokes a specific member of the current Type.

多載

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[])

使用指定的繫結條件約束並符合指定的引數清單,來叫用指定的成員。Invokes the specified member, using the specified binding constraints and matching the specified argument list.

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

使用指定的繫結條件約束並符合指定的引數清單和文化特性 (Culture) 來叫用指定的成員。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[])

在衍生類別中覆寫時,使用指定的繫結條件約束並符合指定的引數清單、修飾詞和文化特性,來叫用指定的成員。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);
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
Public MustOverride Function InvokeMember (name As String, invokeAttr As BindingFlags, binder As Binder, target As Object, args As Object(), modifiers As ParameterModifier(), culture As CultureInfo, namedParameters As String()) As Object

參數

name
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

列舉值的位元組合,用來指定搜尋的執行方式。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

定義一組屬性並啟用繫結的物件,可包含多載方法的選擇、引數類型的強制,以及透過反映的成員引動過程。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- Null 參考 (在 Visual Basic 中為 Nothing),可使用 DefaultBinderA 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

要在其上叫用指定成員的物件。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 物件,代表要使用的全球化地區設定,進行特定地區設定轉換時可能需要這個物件,例如將數值的 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- Null 參考 (Visual Basic 中的Nothing ),可使用目前執行緒的 CultureInfoA 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.

傳回

Object

表示叫用的成員之傳回值的物件。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 包含與 CreateInstanceInvokeMethodGetFieldSetFieldGetProperty合併的 SetPropertyinvokeAttr 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 包含與 InvokeMethodSetField 合併的 SetPropertyinvokeAttr contains InvokeMethod combined with SetField or SetProperty.

-或--or- invokeAttr 包含 SetFieldargs 具有一個以上的項目。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- 其中一個具名參數陣列包含的字串是 nullOne 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 (modifiers) 的和 culture 參數,但您可以使用抽象 System.Reflection.Binder 類來撰寫可處理和的自訂 modifiers culture 系結器。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 interop 呼叫時才會使用,而且只會處理以傳址方式傳遞的參數。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. 已忽略 namename is ignored. 與其他調用旗標無效。Not valid with other invocation flags.

  • InvokeMethod 以叫用方法,但不是函式或類型初始化運算式。InvokeMethod to invoke a method, but not a constructor or a type initializer. 使用或無效 SetField SetPropertyNot valid with SetField or SetProperty. 如果 InvokeMethod 指定了,則會 BindingFlags.Public BindingFlags.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. 這些方法會根據要求的系結類型 BindingFlags ( (值 InvokeMethodGetProperty 和) 來找到。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.ValueTo 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 ,否則可能不會使用方法省略選擇性參數 InvokeUnless 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 保留的陣列中的字串 "z" 變更為字串 "b"。This will change string "z" in the array that F holds to string "b".

注意

從 .NET Framework 2.0 Service Pack 1 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且非公用成員的授權集受限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

另請參閱

適用於

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

使用指定的繫結條件約束並符合指定的引數清單,來叫用指定的成員。Invokes the specified member, using the specified binding constraints and matching the specified argument list.

public:
 System::Object ^ InvokeMember(System::String ^ name, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Object ^ target, cli::array <System::Object ^> ^ args);
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);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args);
member this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] -> obj
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
Public Function InvokeMember (name As String, invokeAttr As BindingFlags, binder As Binder, target As Object, args As Object()) As Object

參數

name
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

列舉值的位元組合,用來指定搜尋的執行方式。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

定義一組屬性並啟用繫結的物件,可包含多載方法的選擇、引數類型的強制,以及透過反映的成員引動過程。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- Null 參考 (在 Visual Basic 中為Nothing ),可使用 DefaultBinderA 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

要在其上叫用指定成員的物件。The object on which to invoke the specified member.

args
Object[]

包含引數的陣列,這些引數會傳遞給要叫用的成員。An array containing the arguments to pass to the member to invoke.

傳回

Object

表示叫用的成員之傳回值的物件。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 包含與 CreateInstanceInvokeMethodGetFieldSetFieldGetProperty合併的 SetPropertyinvokeAttr 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 包含與 InvokeMethodSetField 合併的 SetPropertyinvokeAttr contains InvokeMethod combined with SetField or SetProperty.

-或--or- invokeAttr 包含 SetFieldargs 具有一個以上的項目。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- 其中一個具名參數陣列包含的字串是 nullOne 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.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

    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

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

備註

注意

您無法使用 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. 已忽略 namename is ignored. 與其他調用旗標無效。Not valid with other invocation flags.

  • InvokeMethod 以叫用方法,但不是函式或類型初始化運算式。InvokeMethod to invoke a method, but not a constructor or a type initializer. 使用或無效 SetField SetPropertyNot valid with SetField or SetProperty. 如果 InvokeMethod 指定了,則會 BindingFlags.Public BindingFlags.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. 這些方法會根據要求的系結類型 BindingFlags ( (值 InvokeMethodGetProperty 和) 來找到。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 保留的陣列中的字串 "z" 變更為字串 "b"。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 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且非公用成員的授權集受限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

另請參閱

適用於

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

使用指定的繫結條件約束並符合指定的引數清單和文化特性 (Culture) 來叫用指定的成員。Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.

public:
 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:
 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);
public object InvokeMember (string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Globalization.CultureInfo culture);
member this.InvokeMember : string * System.Reflection.BindingFlags * System.Reflection.Binder * obj * obj[] * System.Globalization.CultureInfo -> obj
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
Public Function InvokeMember (name As String, invokeAttr As BindingFlags, binder As Binder, target As Object, args As Object(), culture As CultureInfo) As Object

參數

name
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

列舉值的位元組合,用來指定搜尋的執行方式。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

定義一組屬性並啟用繫結的物件,可包含多載方法的選擇、引數類型的強制,以及透過反映的成員引動過程。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- Null 參考 (在 Visual Basic 中為Nothing ),可使用 DefaultBinderA 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

要在其上叫用指定成員的物件。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

表示要使用之全球化地區設定的物件,它可能是地區設定特性轉換所需要的,例如將數值 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- Null 參考 (Visual Basic 中的Nothing ),可使用目前執行緒的 CultureInfoA null reference (Nothing in Visual Basic) to use the current thread's CultureInfo.

傳回

Object

表示叫用的成員之傳回值的物件。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 包含與 CreateInstanceInvokeMethodGetFieldSetFieldGetProperty合併的 SetPropertyinvokeAttr 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 包含與 InvokeMethodSetField 合併的 SetPropertyinvokeAttr contains InvokeMethod combined with SetField or SetProperty.

-或--or- invokeAttr 包含 SetFieldargs 具有一個以上的項目。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- 其中一個具名參數陣列包含的字串是 nullOne 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 類來撰寫執行處理常式的自訂 culture 系結器。Although 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. 已忽略 namename is ignored. 與其他調用旗標無效。Not valid with other invocation flags.

  • InvokeMethod 以叫用方法,但不是函式或類型初始化運算式。InvokeMethod to invoke a method, but not a constructor or a type initializer. 使用或無效 SetField SetPropertyNot valid with SetField or SetProperty. 如果 InvokeMethod 指定了,則會 BindingFlags.Public BindingFlags.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. 這些方法會根據要求的系結類型 BindingFlags ( (值 InvokeMethodGetProperty 和) 來找到。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 保留的陣列中的字串 "z" 變更為字串 "b"。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 開始,如果呼叫者已被授 ReflectionPermission 與旗標, ReflectionPermissionFlag.RestrictedMemberAccess 且非公用成員的授權集受限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用成員。Starting with the .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 或更新版本為目標。To use this functionality, your application should target the .NET Framework 3.5 or later.

另請參閱

適用於