MethodBase.Invoke 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
调用此 MethodInfo 实例反映的方法或构造函数。
重载
| 名称 | 说明 |
|---|---|
| Invoke(Object, Object[]) |
使用指定的参数调用由当前实例表示的方法或构造函数。 |
| Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) |
在派生类中重写时,使用给定参数调用反射的方法或构造函数。 |
Invoke(Object, Object[])
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
使用指定的参数调用由当前实例表示的方法或构造函数。
public:
virtual System::Object ^ Invoke(System::Object ^ obj, cli::array <System::Object ^> ^ parameters);
public:
System::Object ^ Invoke(System::Object ^ obj, cli::array <System::Object ^> ^ parameters);
public virtual object Invoke(object obj, object[] parameters);
public object? Invoke(object? obj, object?[]? parameters);
public object Invoke(object obj, object[] parameters);
abstract member Invoke : obj * obj[] -> obj
override this.Invoke : obj * obj[] -> obj
member this.Invoke : obj * obj[] -> obj
Public Overridable Function Invoke (obj As Object, parameters As Object()) As Object
Public Function Invoke (obj As Object, parameters As Object()) As Object
参数
- obj
- Object
要对其调用方法或构造函数的对象。 如果方法是静态的,则忽略此参数。 如果构造函数是静态的,则此参数必须是 null 定义构造函数的类的实例。
- parameters
- Object[]
已调用的方法或构造函数的参数列表。 这是一个对象数组,其数字、顺序和类型与要调用的方法或构造函数的参数相同。 如果没有参数, parameters 应为 null。
如果此实例表示的方法或构造函数采用参数 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)方法重载、传递和invokeAttrnull传递Defaultbinder方法culture。
如果调用的方法引发异常,该方法 Exception.GetBaseException 将返回原始异常。
若要使用其MethodInfo对象调用静态方法,请传递 null 。obj
注释
如果此方法重载用于调用实例构造函数,则 obj 为该对象重新初始化;也就是说,将执行所有实例初始值设定项。 返回值为 null. 如果调用类构造函数,则重新初始化该类;也就是说,执行所有类初始值设定项。 返回值为 null.
注释
如果使用标志授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess调用方,并且非公共成员的授予集仅限于调用方授予集或子集,则此方法可用于访问非公共成员。 (请参阅反射的安全注意事项。)若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。
如果反射方法的参数是值类型,并且相应的参数是parametersnull,则运行时将传递值类型的零初始化实例。
另请参阅
- BindingFlags
- Missing
- InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])
适用于
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
- Source:
- MethodBase.cs
在派生类中重写时,使用给定参数调用反射的方法或构造函数。
public:
abstract System::Object ^ Invoke(System::Object ^ obj, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ parameters, System::Globalization::CultureInfo ^ culture);
public abstract object? Invoke(object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? parameters, System.Globalization.CultureInfo? culture);
public abstract object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture);
abstract member Invoke : obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj
Public MustOverride Function Invoke (obj As Object, invokeAttr As BindingFlags, binder As Binder, parameters As Object(), culture As CultureInfo) As Object
参数
- obj
- Object
要对其调用方法或构造函数的对象。 如果方法是静态的,则忽略此参数。 如果构造函数是静态的,则此参数必须是 null 定义构造函数的类的实例。
- invokeAttr
- BindingFlags
位掩码,它是来自 BindingFlags0 个或更多位标志的组合。
- binder
- Binder
一个对象,它允许绑定、强制参数类型、调用成员,以及通过反射检索 MemberInfo 对象。
binder如果是null,则使用默认绑定器。
- parameters
- Object[]
已调用的方法或构造函数的参数列表。 这是一个对象数组,其数字、顺序和类型与要调用的方法或构造函数的参数相同。 如果没有参数,应为
如果此实例表示的方法或构造函数采用 ByRef 参数,则该参数不需要特殊属性才能使用此函数调用方法或构造函数。 未使用值显式初始化的此数组中的任何对象都将包含该对象类型的默认值。 对于引用类型元素,此值为 null. 对于值类型元素,此值为 0、0.0 或 false,具体取决于特定的元素类型。
- culture
- CultureInfo
用于控制类型的强制的实例 CultureInfo 。 如果是, null则 CultureInfo 使用当前线程。 (这需要将表示 1000 Double 的字符串转换为值,例如,因为 1000 由不同的区域性以不同的方式表示)。
返回
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 。
注释
如果此方法重载用于调用实例构造函数,则 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")。
如果当前方法的参数是值类型,并且相应的参数为
在调用虚拟方法时,反射使用动态方法查找。 例如,假设类 B 继承自类 A,同时实现名为 M 的虚拟方法。现在假设你有一个 MethodInfo 对象,表示类 A 上的 M。如果使用 Invoke 该方法对类型 B 的对象调用 M,反射将使用类 B 提供的实现。即使类型 B 的对象被强制转换为 A,也会使用 B 类给出的实现(请参阅下面的代码示例)。
另一方面,如果该方法是非虚拟的,则反射将使用从 MethodInfo 中获取的类型给出的实现,而不考虑作为目标传递的对象的类型。
对于完全受信任的代码,将忽略访问限制。 也就是说,每当完全信任代码时,都可以通过反射访问和调用专用构造函数、方法、字段和属性。
如果调用的方法引发异常,该方法 Exception.GetBaseException 将返回原始异常。
注释
如果使用标志授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess调用方,并且非公共成员的授予集仅限于调用方授予集或子集,则此方法可用于访问非公共成员。 (请参阅反射的安全注意事项。)若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。
另请参阅
- InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])
- 动态加载和使用类型