MethodBase.Invoke 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
會呼叫本 MethodInfo 實例所反映的方法或建構器。
多載
| 名稱 | Description |
|---|---|
| Invoke(Object, Object[]) |
呼叫目前實例所代表的方法或建構子,使用指定的參數。 |
| Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) |
當在導出類別中被覆寫時,會呼叫反映的方法或構造子,並以給定參數進行。 |
Invoke(Object, Object[])
呼叫目前實例所代表的方法或建構子,使用指定的參數。
public:
virtual System::Object ^ Invoke(System::Object ^ obj, cli::array <System::Object ^> ^ parameters);
public:
System::Object ^ Invoke(System::Object ^ obj, cli::array <System::Object ^> ^ parameters);
public virtual object Invoke(object obj, object[] parameters);
public object? Invoke(object? obj, object?[]? parameters);
public object Invoke(object obj, object[] parameters);
abstract member Invoke : obj * obj[] -> obj
override this.Invoke : obj * obj[] -> obj
member this.Invoke : obj * obj[] -> obj
Public Overridable Function Invoke (obj As Object, parameters As Object()) As Object
Public Function Invoke (obj As Object, parameters As Object()) As Object
參數
- obj
- Object
用於呼叫方法或建構子的物件。 若方法為靜態,則忽略此參數。 若建構子是靜態的,則該參數必須是 null 定義建構子的類別的實例。
- parameters
- Object[]
一個用於調用的方法或建構子的參數清單。 這是一個與要呼叫的方法或建構子參數數量、順序與類型相同的物件陣列。 若無參數,則 parameters 應為 null。
如果這個實例所代表的方法或建構子接受 ref 參數(ByRef 在 Visual Basic 中),則不需要為該參數設置特殊屬性,就能用這個函式呼叫該方法或建構子。 這個陣列中任何未明確初始化值的物件,都會包含該物件類型的預設值。 對於參考型元素,此值為 null。 對於值型元素,預設值為 0、0.0 或 false,視具體元素類型而定。
傳回
包含所呼叫方法回傳值的物件,或 null 在建構子的情況下。
實作
例外狀況
參數 obj 為 , null 且方法不是靜態的。
-或-
該方法不會被類別宣告或繼承 obj。
-或-
會呼叫靜態建構子,既 obj 不是 null 宣告建構子的類別實例。
陣列中的 parameters 元素與此實例所反映的方法或建構子簽名不符。
陣 parameters 列的參數數不正確。
呼叫者無權執行目前實例所代表的方法或構造子。
宣告該方法的類型是開放的泛型。 也就是說,該 ContainsGenericParameters 屬性會回傳 true 宣告型別的屬性。
目前的實例是一個 MethodBuilder。
範例
以下程式碼範例展示了利用反射法進行動態方法查找。 請注意,你不能用 MethodInfo 基底類別的物件來呼叫衍生類別中被覆寫的方法,因為延遲綁定無法解析覆寫。
using System;
using System.Reflection;
public class MagicClass
{
private int magicBaseValue;
public MagicClass()
{
magicBaseValue = 9;
}
public int ItsMagic(int preMagic)
{
return preMagic * magicBaseValue;
}
}
public class TestMethodInfo
{
public static void Main()
{
// Get the constructor and create an instance of MagicClass
Type magicType = Type.GetType("MagicClass");
ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
object magicClassObject = magicConstructor.Invoke(new object[]{});
// Get the ItsMagic method and invoke with a parameter value of 100
MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});
Console.WriteLine("MethodInfo.Invoke() Example\n");
Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
}
}
// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900
Imports System.Reflection
Public Class MagicClass
Private magicBaseValue As Integer
Public Sub New()
magicBaseValue = 9
End Sub
Public Function ItsMagic(preMagic As Integer) As Integer
Return preMagic * magicBaseValue
End Function
End Class
Public Class TestMethodInfo
Public Shared Sub Main()
' Get the constructor and create an instance of MagicClass
Dim magicType As Type = Type.GetType("MagicClass")
Dim magicConstructor As ConstructorInfo = magicType.GetConstructor(Type.EmptyTypes)
Dim magicClassObject As Object = magicConstructor.Invoke(New Object(){})
' Get the ItsMagic method and invoke with a parameter value of 100
Dim magicMethod As MethodInfo = magicType.GetMethod("ItsMagic")
Dim magicValue As Object = magicMethod.Invoke(magicClassObject, New Object(){100})
Console.WriteLine("MethodInfo.Invoke() Example" + Environment.NewLine)
Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue)
End Sub
End Class
' The example program gives the following output:
'
' MethodInfo.Invoke() Example
'
' MagicClass.ItsMagic() returned: 900
備註
這是一種方便的方法,稱為 Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) 方法過載,通過 Default 和 invokeAttrnull ,且 binderculture。
如果被呼叫的方法拋出異常,該 Exception.GetBaseException 方法會回傳原始例外。
若要使用物件MethodInfo呼叫靜態方法,請通過 null 。obj
Note
如果使用此方法過載來呼叫實例建構子,所提供的 obj 物件會被重新初始化;也就是說,所有實例初始化器都會被執行。 返回值為 null。 若呼叫類別建構子,該類別會被重新初始化;也就是說,所有類別初始化器都會被執行。 返回值為 null。
Note
若呼叫者已獲得ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess該旗標,且非公開成員的授權集限制於呼叫者的授權集或其子集,此方法可用來存取非公開成員。 (參見 安全考量 以促進反思)要使用此功能,您的應用程式應針對 .NET Framework 3.5 或更新版本。
若反射方法的參數為值型別,且對應參數 parameters 為 null,執行時會通過一個零初始化的值型別實例。
另請參閱
- BindingFlags
- Missing
- InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])
適用於
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)
當在導出類別中被覆寫時,會呼叫反映的方法或構造子,並以給定參數進行。
public:
abstract System::Object ^ Invoke(System::Object ^ obj, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ parameters, System::Globalization::CultureInfo ^ culture);
public abstract object? Invoke(object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? parameters, System.Globalization.CultureInfo? culture);
public abstract object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture);
abstract member Invoke : obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj
Public MustOverride Function Invoke (obj As Object, invokeAttr As BindingFlags, binder As Binder, parameters As Object(), culture As CultureInfo) As Object
參數
- obj
- Object
用於呼叫方法或建構子的物件。 若方法為靜態,則忽略此參數。 若建構子是靜態的,則該參數必須是 null 定義建構子的類別的實例。
- invokeAttr
- BindingFlags
一個由 中 BindingFlags0 個或多個位元旗組成的位元遮罩。
- binder
- Binder
一個能夠約束、強制參數類型、調用成員,以及透過反射檢索 MemberInfo 物件的物件。 若 binder , null則使用預設的綁定器。
- parameters
- Object[]
一個用於調用的方法或建構子的參數清單。 這是一個與要呼叫的方法或建構子參數數量、順序與類型相同的物件陣列。 若無參數,則應為 null。
如果這個實例所代表的方法或建構子採用 ByRef 參數,則不需要該參數有特殊屬性即可呼叫使用此函式的方法或建構子。 這個陣列中任何未明確初始化值的物件,都會包含該物件類型的預設值。 對於參考型元素,此值為 null。 對於值型元素,這個值會根據特定元素類型而定,分別是0、0.0或 false。
- culture
- CultureInfo
一個用來規範類型強制的實例 CultureInfo 。 如果是 null, CultureInfo 則使用當前執行緒的 。 (例如,將代表 1000 Double 的字串轉換為值是必要的,因為不同文化對 1000 的表示方式不同。)
傳回
A Object 包含被調用方法的回傳值,或 null 在建構子的情況下,或 null 若方法的回傳型別為 void。 在呼叫方法或建構子前, Invoke 會檢查使用者是否有存取權限並驗證參數有效。
實作
例外狀況
參數 obj 為 , null 且方法不是靜態的。
-或-
該方法不會被類別宣告或繼承 obj。
-或-
會呼叫靜態建構子,既 obj 不是 null 宣告建構子的類別實例。
參數的 parameters 類型與此實例所反映的方法或建構子簽名不符。
陣 parameters 列的參數數不正確。
被呼叫的方法或建構子會拋出例外。
呼叫者無權執行目前實例所代表的方法或構造子。
宣告該方法的類型是開放的泛型。 也就是說,該 ContainsGenericParameters 屬性會回傳 true 宣告型別的屬性。
範例
以下範例展示了使用過載 的 Type.InvokeMember類別所有成員System.Reflection.Binder。 私密方法 CanConvertFrom 則是為特定類型尋找相容型別。 關於在自訂綁定情境中調用成員的另一個範例,請參見 動態載入與使用類型。
using System;
using System.Reflection;
using System.Globalization;
public class MyBinder : Binder
{
public MyBinder() : base()
{
}
private class BinderState
{
public object[] args;
}
public override FieldInfo BindToField(
BindingFlags bindingAttr,
FieldInfo[] match,
object value,
CultureInfo culture
)
{
if(match == null)
throw new ArgumentNullException("match");
// Get a field for which the value parameter can be converted to the specified field type.
for(int i = 0; i < match.Length; i++)
if(ChangeType(value, match[i].FieldType, culture) != null)
return match[i];
return null;
}
public override MethodBase BindToMethod(
BindingFlags bindingAttr,
MethodBase[] match,
ref object[] args,
ParameterModifier[] modifiers,
CultureInfo culture,
string[] names,
out object state
)
{
// Store the arguments to the method in a state object.
BinderState myBinderState = new BinderState();
object[] arguments = new Object[args.Length];
args.CopyTo(arguments, 0);
myBinderState.args = arguments;
state = myBinderState;
if(match == null)
throw new ArgumentNullException();
// Find a method that has the same parameters as those of the args parameter.
for(int i = 0; i < match.Length; i++)
{
// Count the number of parameters that match.
int count = 0;
ParameterInfo[] parameters = match[i].GetParameters();
// Go on to the next method if the number of parameters do not match.
if(args.Length != parameters.Length)
continue;
// Match each of the parameters that the user expects the method to have.
for(int j = 0; j < args.Length; j++)
{
// If the names parameter is not null, then reorder args.
if(names != null)
{
if(names.Length != args.Length)
throw new ArgumentException("names and args must have the same number of elements.");
for(int k = 0; k < names.Length; k++)
if(String.Compare(parameters[j].Name, names[k].ToString()) == 0)
args[j] = myBinderState.args[k];
}
// Determine whether the types specified by the user can be converted to the parameter type.
if(ChangeType(args[j], parameters[j].ParameterType, culture) != null)
count += 1;
else
break;
}
// Determine whether the method has been found.
if(count == args.Length)
return match[i];
}
return null;
}
public override object ChangeType(
object value,
Type myChangeType,
CultureInfo culture
)
{
// Determine whether the value parameter can be converted to a value of type myType.
if(CanConvertFrom(value.GetType(), myChangeType))
// Return the converted object.
return Convert.ChangeType(value, myChangeType);
else
// Return null.
return null;
}
public override void ReorderArgumentArray(
ref object[] args,
object state
)
{
// Return the args that had been reordered by BindToMethod.
((BinderState)state).args.CopyTo(args, 0);
}
public override MethodBase SelectMethod(
BindingFlags bindingAttr,
MethodBase[] match,
Type[] types,
ParameterModifier[] modifiers
)
{
if(match == null)
throw new ArgumentNullException("match");
for(int i = 0; i < match.Length; i++)
{
// Count the number of parameters that match.
int count = 0;
ParameterInfo[] parameters = match[i].GetParameters();
// Go on to the next method if the number of parameters do not match.
if(types.Length != parameters.Length)
continue;
// Match each of the parameters that the user expects the method to have.
for(int j = 0; j < types.Length; j++)
// Determine whether the types specified by the user can be converted to parameter type.
if(CanConvertFrom(types[j], parameters[j].ParameterType))
count += 1;
else
break;
// Determine whether the method has been found.
if(count == types.Length)
return match[i];
}
return null;
}
public override PropertyInfo SelectProperty(
BindingFlags bindingAttr,
PropertyInfo[] match,
Type returnType,
Type[] indexes,
ParameterModifier[] modifiers
)
{
if(match == null)
throw new ArgumentNullException("match");
for(int i = 0; i < match.Length; i++)
{
// Count the number of indexes that match.
int count = 0;
ParameterInfo[] parameters = match[i].GetIndexParameters();
// Go on to the next property if the number of indexes do not match.
if(indexes.Length != parameters.Length)
continue;
// Match each of the indexes that the user expects the property to have.
for(int j = 0; j < indexes.Length; j++)
// Determine whether the types specified by the user can be converted to index type.
if(CanConvertFrom(indexes[j], parameters[j].ParameterType))
count += 1;
else
break;
// Determine whether the property has been found.
if(count == indexes.Length)
// Determine whether the return type can be converted to the properties type.
if(CanConvertFrom(returnType, match[i].PropertyType))
return match[i];
else
continue;
}
return null;
}
// Determines whether type1 can be converted to type2. Check only for primitive types.
private bool CanConvertFrom(Type type1, Type type2)
{
if(type1.IsPrimitive && type2.IsPrimitive)
{
TypeCode typeCode1 = Type.GetTypeCode(type1);
TypeCode typeCode2 = Type.GetTypeCode(type2);
// If both type1 and type2 have the same type, return true.
if(typeCode1 == typeCode2)
return true;
// Possible conversions from Char follow.
if(typeCode1 == TypeCode.Char)
switch(typeCode2)
{
case TypeCode.UInt16 : return true;
case TypeCode.UInt32 : return true;
case TypeCode.Int32 : return true;
case TypeCode.UInt64 : return true;
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from Byte follow.
if(typeCode1 == TypeCode.Byte)
switch(typeCode2)
{
case TypeCode.Char : return true;
case TypeCode.UInt16 : return true;
case TypeCode.Int16 : return true;
case TypeCode.UInt32 : return true;
case TypeCode.Int32 : return true;
case TypeCode.UInt64 : return true;
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from SByte follow.
if(typeCode1 == TypeCode.SByte)
switch(typeCode2)
{
case TypeCode.Int16 : return true;
case TypeCode.Int32 : return true;
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from UInt16 follow.
if(typeCode1 == TypeCode.UInt16)
switch(typeCode2)
{
case TypeCode.UInt32 : return true;
case TypeCode.Int32 : return true;
case TypeCode.UInt64 : return true;
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from Int16 follow.
if(typeCode1 == TypeCode.Int16)
switch(typeCode2)
{
case TypeCode.Int32 : return true;
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from UInt32 follow.
if(typeCode1 == TypeCode.UInt32)
switch(typeCode2)
{
case TypeCode.UInt64 : return true;
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from Int32 follow.
if(typeCode1 == TypeCode.Int32)
switch(typeCode2)
{
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from UInt64 follow.
if(typeCode1 == TypeCode.UInt64)
switch(typeCode2)
{
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from Int64 follow.
if(typeCode1 == TypeCode.Int64)
switch(typeCode2)
{
case TypeCode.Single : return true;
case TypeCode.Double : return true;
default : return false;
}
// Possible conversions from Single follow.
if(typeCode1 == TypeCode.Single)
switch(typeCode2)
{
case TypeCode.Double : return true;
default : return false;
}
}
return false;
}
}
public class MyClass1
{
public short myFieldB;
public int myFieldA;
public void MyMethod(long i, char k)
{
Console.WriteLine("\nThis is MyMethod(long i, char k)");
}
public void MyMethod(long i, long j)
{
Console.WriteLine("\nThis is MyMethod(long i, long j)");
}
}
public class Binder_Example
{
public static void Main()
{
// Get the type of MyClass1.
Type myType = typeof(MyClass1);
// Get the instance of MyClass1.
MyClass1 myInstance = new MyClass1();
Console.WriteLine("\nDisplaying the results of using the MyBinder binder.\n");
// Get the method information for MyMethod.
MethodInfo myMethod = myType.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance,
new MyBinder(), new Type[] {typeof(short), typeof(short)}, null);
Console.WriteLine(myMethod);
// Invoke MyMethod.
myMethod.Invoke(myInstance, BindingFlags.InvokeMethod, new MyBinder(), new Object[] {(int)32, (int)32}, CultureInfo.CurrentCulture);
}
}
Imports System.Reflection
Imports System.Globalization
Public Class MyBinder
Inherits Binder
Public Sub New()
MyBase.new()
End Sub
Private Class BinderState
Public args() As Object
End Class
Public Overrides Function BindToField(ByVal bindingAttr As BindingFlags, ByVal match() As FieldInfo, ByVal value As Object, ByVal culture As CultureInfo) As FieldInfo
If match Is Nothing Then
Throw New ArgumentNullException("match")
End If
' Get a field for which the value parameter can be converted to the specified field type.
Dim i As Integer
For i = 0 To match.Length - 1
If Not (ChangeType(value, match(i).FieldType, culture) Is Nothing) Then
Return match(i)
End If
Next i
Return Nothing
End Function 'BindToField
Public Overrides Function BindToMethod(ByVal bindingAttr As BindingFlags, ByVal match() As MethodBase, ByRef args() As Object, ByVal modifiers() As ParameterModifier, ByVal culture As CultureInfo, ByVal names() As String, ByRef state As Object) As MethodBase
' Store the arguments to the method in a state object.
Dim myBinderState As New BinderState()
Dim arguments() As Object = New [Object](args.Length) {}
args.CopyTo(arguments, 0)
myBinderState.args = arguments
state = myBinderState
If match Is Nothing Then
Throw New ArgumentNullException()
End If
' Find a method that has the same parameters as those of args.
Dim i As Integer
For i = 0 To match.Length - 1
' Count the number of parameters that match.
Dim count As Integer = 0
Dim parameters As ParameterInfo() = match(i).GetParameters()
' Go on to the next method if the number of parameters do not match.
If args.Length <> parameters.Length Then
GoTo ContinueFori
End If
' Match each of the parameters that the user expects the method to have.
Dim j As Integer
For j = 0 To args.Length - 1
' If names is not null, then reorder args.
If Not (names Is Nothing) Then
If names.Length <> args.Length Then
Throw New ArgumentException("names and args must have the same number of elements.")
End If
Dim k As Integer
For k = 0 To names.Length - 1
If String.Compare(parameters(j).Name, names(k).ToString()) = 0 Then
args(j) = myBinderState.args(k)
End If
Next k
End If ' Determine whether the types specified by the user can be converted to parameter type.
If Not (ChangeType(args(j), parameters(j).ParameterType, culture) Is Nothing) Then
count += 1
Else
Exit For
End If
Next j
' Determine whether the method has been found.
If count = args.Length Then
Return match(i)
End If
ContinueFori:
Next i
Return Nothing
End Function 'BindToMethod
Public Overrides Function ChangeType(ByVal value As Object, ByVal myChangeType As Type, ByVal culture As CultureInfo) As Object
' Determine whether the value parameter can be converted to a value of type myType.
If CanConvertFrom(value.GetType(), myChangeType) Then
' Return the converted object.
Return Convert.ChangeType(value, myChangeType)
' Return null.
Else
Return Nothing
End If
End Function 'ChangeType
Public Overrides Sub ReorderArgumentArray(ByRef args() As Object, ByVal state As Object)
'Redimension the array to hold the state values.
ReDim args(CType(state, BinderState).args.Length)
' Return the args that had been reordered by BindToMethod.
CType(state, BinderState).args.CopyTo(args, 0)
End Sub
Public Overrides Function SelectMethod(ByVal bindingAttr As BindingFlags, ByVal match() As MethodBase, ByVal types() As Type, ByVal modifiers() As ParameterModifier) As MethodBase
If match Is Nothing Then
Throw New ArgumentNullException("match")
End If
Dim i As Integer
For i = 0 To match.Length - 1
' Count the number of parameters that match.
Dim count As Integer = 0
Dim parameters As ParameterInfo() = match(i).GetParameters()
' Go on to the next method if the number of parameters do not match.
If types.Length <> parameters.Length Then
GoTo ContinueFori
End If
' Match each of the parameters that the user expects the method to have.
Dim j As Integer
For j = 0 To types.Length - 1
' Determine whether the types specified by the user can be converted to parameter type.
If CanConvertFrom(types(j), parameters(j).ParameterType) Then
count += 1
Else
Exit For
End If
Next j ' Determine whether the method has been found.
If count = types.Length Then
Return match(i)
End If
ContinueFori:
Next i
Return Nothing
End Function 'SelectMethod
Public Overrides Function SelectProperty(ByVal bindingAttr As BindingFlags, ByVal match() As PropertyInfo, ByVal returnType As Type, ByVal indexes() As Type, ByVal modifiers() As ParameterModifier) As PropertyInfo
If match Is Nothing Then
Throw New ArgumentNullException("match")
End If
Dim i As Integer
For i = 0 To match.Length - 1
' Count the number of indexes that match.
Dim count As Integer = 0
Dim parameters As ParameterInfo() = match(i).GetIndexParameters()
' Go on to the next property if the number of indexes do not match.
If indexes.Length <> parameters.Length Then
GoTo ContinueFori
End If
' Match each of the indexes that the user expects the property to have.
Dim j As Integer
For j = 0 To indexes.Length - 1
' Determine whether the types specified by the user can be converted to index type.
If CanConvertFrom(indexes(j), parameters(j).ParameterType) Then
count += 1
Else
Exit For
End If
Next j ' Determine whether the property has been found.
If count = indexes.Length Then
' Determine whether the return type can be converted to the properties type.
If CanConvertFrom(returnType, match(i).PropertyType) Then
Return match(i)
Else
GoTo ContinueFori
End If
End If
ContinueFori:
Next i
Return Nothing
End Function 'SelectProperty
' Determine whether type1 can be converted to type2. Check only for primitive types.
Private Function CanConvertFrom(ByVal type1 As Type, ByVal type2 As Type) As Boolean
If type1.IsPrimitive And type2.IsPrimitive Then
Dim typeCode1 As TypeCode = Type.GetTypeCode(type1)
Dim typeCode2 As TypeCode = Type.GetTypeCode(type2)
' If both type1 and type2 have same type, return true.
If typeCode1 = typeCode2 Then
Return True
End If ' Possible conversions from Char follow.
If typeCode1 = TypeCode.Char Then
Select Case typeCode2
Case TypeCode.UInt16
Return True
Case TypeCode.UInt32
Return True
Case TypeCode.Int32
Return True
Case TypeCode.UInt64
Return True
Case TypeCode.Int64
Return True
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from Byte follow.
If typeCode1 = TypeCode.Byte Then
Select Case typeCode2
Case TypeCode.Char
Return True
Case TypeCode.UInt16
Return True
Case TypeCode.Int16
Return True
Case TypeCode.UInt32
Return True
Case TypeCode.Int32
Return True
Case TypeCode.UInt64
Return True
Case TypeCode.Int64
Return True
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from SByte follow.
If typeCode1 = TypeCode.SByte Then
Select Case typeCode2
Case TypeCode.Int16
Return True
Case TypeCode.Int32
Return True
Case TypeCode.Int64
Return True
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from UInt16 follow.
If typeCode1 = TypeCode.UInt16 Then
Select Case typeCode2
Case TypeCode.UInt32
Return True
Case TypeCode.Int32
Return True
Case TypeCode.UInt64
Return True
Case TypeCode.Int64
Return True
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from Int16 follow.
If typeCode1 = TypeCode.Int16 Then
Select Case typeCode2
Case TypeCode.Int32
Return True
Case TypeCode.Int64
Return True
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from UInt32 follow.
If typeCode1 = TypeCode.UInt32 Then
Select Case typeCode2
Case TypeCode.UInt64
Return True
Case TypeCode.Int64
Return True
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from Int32 follow.
If typeCode1 = TypeCode.Int32 Then
Select Case typeCode2
Case TypeCode.Int64
Return True
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from UInt64 follow.
If typeCode1 = TypeCode.UInt64 Then
Select Case typeCode2
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from Int64 follow.
If typeCode1 = TypeCode.Int64 Then
Select Case typeCode2
Case TypeCode.Single
Return True
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If ' Possible conversions from Single follow.
If typeCode1 = TypeCode.Single Then
Select Case typeCode2
Case TypeCode.Double
Return True
Case Else
Return False
End Select
End If
End If
Return False
End Function 'CanConvertFrom
End Class
Public Class MyClass1
Public myFieldB As Short
Public myFieldA As Integer
Public Overloads Sub MyMethod(ByVal i As Long, ByVal k As Char)
Console.WriteLine(ControlChars.NewLine & "This is MyMethod(long i, char k).")
End Sub
Public Overloads Sub MyMethod(ByVal i As Long, ByVal j As Long)
Console.WriteLine(ControlChars.NewLine & "This is MyMethod(long i, long j).")
End Sub
End Class
Public Class Binder_Example
Public Shared Sub Main()
' Get the type of MyClass1.
Dim myType As Type = GetType(MyClass1)
' Get the instance of MyClass1.
Dim myInstance As New MyClass1()
Console.WriteLine(ControlChars.Cr & "Displaying the results of using the MyBinder binder.")
Console.WriteLine()
' Get the method information for MyMethod.
Dim myMethod As MethodInfo = myType.GetMethod("MyMethod", BindingFlags.Public Or BindingFlags.Instance, New MyBinder(), New Type() {GetType(Short), GetType(Short)}, Nothing)
Console.WriteLine(MyMethod)
' Invoke MyMethod.
myMethod.Invoke(myInstance, BindingFlags.InvokeMethod, New MyBinder(), New [Object]() {CInt(32), CInt(32)}, CultureInfo.CurrentCulture)
End Sub
End Class
備註
此方法動態調用此實例反映的方法 obj,並傳遞指定的參數。 若方法為靜態,則忽略該 obj 參數。 對於非靜態方法,應該 obj 是繼承或宣告該方法的類別實例,且必須與該類別相同型別。 若方法無參數,則 的 parameters 值應為 null。 否則,元素 parameters 的數量、類型與順序應與本實例所反映的方法參數數量、類型及順序相同。
你在呼叫 時 Invoke不得遺漏可選參數。 若要呼叫方法並省略可選參數,請 Type.InvokeMember call 。
Note
如果使用此方法過載來呼叫實例建構子,所提供的 obj 物件會被重新初始化;也就是說,所有實例初始化器都會被執行。 返回值為 null。 若呼叫類別建構子,該類別會被重新初始化;也就是說,所有類別初始化器都會被執行。 返回值為 null。
對於以值傳遞的原始參數,則會進行正常展寬(例如 Int16 -> Int32)。 對於以值傳遞的參考參數,允許一般的參考擴展(導出類別到基底類別,基底類別到介面型)。 然而,對於通過參照的原始參數,這些類型必須完全匹配。 對於參考通過參考參數,正常的寬頻仍然適用。
例如,若此實例反映的方法宣告為 public boolean Compare(String a, String b),則 parameters 應為長度為 2 Objects 的陣列,使得 parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2")。
若目前方法的參數為值型別,且對應參數 parameters 為 null,執行時會傳遞一個零初始化的值型別實例。
反射在呼叫虛擬方法時會使用動態方法查找。 例如,假設類別 B 繼承自類別 A,且兩者都實作了一個名為 M 的虛擬方法。現在假設你有一個 MethodInfo 物件代表類別 A 上的 M。如果你用 Invoke M 的方法對型別 B 的物件呼叫 M,則反射會使用類別 B 給出的實作。即使物件類型 B 被鑄造為 A,仍會使用類別 B 所提供的實作(見下方程式碼範例)。
另一方面,若方法非虛擬,則反射會使用取得 MethodInfo 物件類型所給的實作,不論傳遞為目標的物件類型為何。
完全信任的程式碼會忽略存取限制。 也就是說,只要程式碼完全信任,私有建構子、方法、欄位和屬性都可以透過反射存取與調用。
如果被呼叫的方法拋出異常,該 Exception.GetBaseException 方法會回傳原始例外。
Note
若呼叫者已獲得ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess該旗標,且非公開成員的授權集限制於呼叫者的授權集或其子集,此方法可用來存取非公開成員。 (參見 安全考量 以促進反思)要使用此功能,您的應用程式應針對 .NET Framework 3.5 或更新版本。
另請參閱
- InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])
- 動態載入與使用 型別