MethodBase.Invoke Metoda
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Vyvolá metodu nebo konstruktor reflektované touto MethodInfo instancí.
Přetížení
| Name | Description |
|---|---|
| Invoke(Object, Object[]) |
Vyvolá metodu nebo konstruktor reprezentovaný aktuální instancí pomocí zadaných parametrů. |
| Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) |
Při přepsání v odvozené třídě vyvolá reflektované metody nebo konstruktoru s danými parametry. |
Invoke(Object, Object[])
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
Vyvolá metodu nebo konstruktor reprezentovaný aktuální instancí pomocí zadaných parametrů.
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
Parametry
- obj
- Object
Objekt, na kterém se má vyvolat metoda nebo konstruktor. Pokud je metoda statická, bude tento argument ignorován. Pokud je konstruktor statický, musí být null tento argument nebo instance třídy, která definuje konstruktor.
- parameters
- Object[]
Seznam argumentů pro vyvolanou metodu nebo konstruktor. Toto je pole objektů se stejným číslem, pořadím a typem jako parametry metody nebo konstruktoru, které se mají vyvolat. Pokud neexistují žádné parametry, parameters měl by být null.
Pokud metoda nebo konstruktor reprezentovaný touto instancí přebírá ref parametr (ByRef v jazyce Visual Basic), není pro tento parametr vyžadován žádný speciální atribut pro vyvolání metody nebo konstruktoru pomocí této funkce. Jakýkoli objekt v tomto poli, který není explicitně inicializován s hodnotou, bude obsahovat výchozí hodnotu pro tento typ objektu. Pro elementy typu odkaz je tato hodnota null. U prvků typu hodnota je výchozí hodnota 0, 0,0 nebo false, v závislosti na konkrétním typu prvku.
Návraty
Objekt obsahující návratovou hodnotu vyvolané metody nebo null v případě konstruktoru.
Implementuje
Výjimky
Parametr obj je null a metoda není statická.
nebo
Metoda není deklarována nebo zděděna třídou třídy obj.
nebo
Vyvolá se statický konstruktor a obj není null ani instancí třídy, která deklarovala konstruktor.
Prvky parameters pole neodpovídají podpisu metody nebo konstruktoru, které tato instance odráží.
Vyvolána metoda nebo konstruktor vyvolá výjimku.
nebo
Aktuální instance je DynamicMethod kód, který obsahuje neověřitelný kód. Viz část "Ověření" v poznámkách pro DynamicMethod.
Matice parameters nemá správný počet argumentů.
Volající nemá oprávnění ke spuštění metody nebo konstruktoru, který je reprezentován aktuální instancí.
Typ, který deklaruje metodu, je otevřený obecný typ. To znamená, že ContainsGenericParameters vlastnost vrátí true pro deklarující typ.
Aktuální instance je .MethodBuilder
Příklady
Následující příklad kódu ukazuje dynamické vyhledávání metod pomocí reflexe. Všimněte si, že nelze použít MethodInfo objekt ze základní třídy k vyvolání přepsání metody v odvozené třídě, protože pozdní vazba nemůže přepsat přepsání.
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
Poznámky
Jedná se o pohodlnou metoduInvoke(Object, BindingFlags, Binder, Object[], CultureInfo), která volá přetížení metody, předávání Default a null pro invokeAttrbinder a culture.
Pokud vyvolaná metoda vyvolá výjimku, Exception.GetBaseException vrátí metoda původní výjimku.
Chcete-li vyvolat statickou metodu pomocí objektu MethodInfo , předejte null pro obj.
Note
Pokud se toto přetížení metody používá k vyvolání konstruktoru instance, objekt zadaný pro obj je znovu inicializován; to znamená, že všechny inicializátory instance jsou provedeny. Vrácená hodnota je null. Pokud je vyvolán konstruktor třídy, třída je znovu inicializována; to znamená, že se spustí všechny inicializátory tříd. Vrácená hodnota je null.
Note
Tuto metodu lze použít pro přístup k neveřejným členům, pokud byl volající udělen ReflectionPermission příznakem ReflectionPermissionFlag.RestrictedMemberAccess a pokud je sada udělení nepřístupných členů omezena na sadu grantů volajícího nebo její podmnožinu. (Viz Aspekty zabezpečení reflexe.) Pokud chcete tuto funkci používat, měla by vaše aplikace cílit na .NET Framework 3.5 nebo novější.
Pokud je parametr reflektované metody typ hodnoty a odpovídající argument je parametersnull, modul runtime předá instanci typu hodnoty inicializované nulou.
Viz také
- BindingFlags
- Missing
- InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])
Platí pro
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
- Zdroj:
- MethodBase.cs
Při přepsání v odvozené třídě vyvolá reflektované metody nebo konstruktoru s danými parametry.
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
Parametry
- obj
- Object
Objekt, na kterém se má vyvolat metoda nebo konstruktor. Pokud je metoda statická, bude tento argument ignorován. Pokud je konstruktor statický, musí být null tento argument nebo instance třídy, která definuje konstruktor.
- invokeAttr
- BindingFlags
Bitová maska, která je kombinací 0 nebo více bitových příznaků z BindingFlags.
- binder
- Binder
Objekt, který umožňuje vazbu, převod typů argumentů, vyvolání členů a načtení MemberInfo objektů prostřednictvím reflexe. Pokud je bindernull, použije se výchozí pořadač.
- parameters
- Object[]
Seznam argumentů pro vyvolanou metodu nebo konstruktor. Toto je pole objektů se stejným číslem, pořadím a typem jako parametry metody nebo konstruktoru, které se mají vyvolat. Pokud neexistují žádné parametry, mělo by to být null.
Pokud metoda nebo konstruktor reprezentovaný touto instancí přebírá parametr ByRef, není pro tento parametr vyžadován žádný speciální atribut pro vyvolání metody nebo konstruktoru pomocí této funkce. Jakýkoli objekt v tomto poli, který není explicitně inicializován s hodnotou, bude obsahovat výchozí hodnotu pro tento typ objektu. Pro elementy typu odkaz je tato hodnota null. U prvků typu hodnota je tato hodnota 0, 0,0 nebo false, v závislosti na konkrétním typu prvku.
- culture
- CultureInfo
Instance CultureInfo sloužící k řízení převodu typů. V takovém případě nullCultureInfo se použije aktuální vlákno. (To je nezbytné k převodu řetězce, který představuje 1000 na Double hodnotu, například protože 1000 je reprezentován odlišně různými jazykovými verzemi.)
Návraty
Obsahující Object návratovou hodnotu vyvolané metody, nebo null v případě konstruktoru, nebo null pokud je voidnávratový typ metody . Před voláním metody nebo konstruktoru zkontroluje, jestli má uživatel oprávnění k přístupu, a ověří, Invoke jestli jsou parametry platné.
Implementuje
Výjimky
Parametr obj je null a metoda není statická.
nebo
Metoda není deklarována nebo zděděna třídou třídy obj.
nebo
Vyvolá se statický konstruktor a obj není null ani instancí třídy, která deklarovala konstruktor.
Typ parametru parameters neodpovídá podpisu metody nebo konstruktoru, který tato instance odráží.
Matice parameters nemá správný počet argumentů.
Vyvolána metoda nebo konstruktor vyvolá výjimku.
Volající nemá oprávnění ke spuštění metody nebo konstruktoru, který je reprezentován aktuální instancí.
Typ, který deklaruje metodu, je otevřený obecný typ. To znamená, že ContainsGenericParameters vlastnost vrátí true pro deklarující typ.
Příklady
Následující příklad ukazuje všechny členy System.Reflection.Binder třídy pomocí přetížení Type.InvokeMember. Privátní metoda CanConvertFrom najde kompatibilní typy pro daný typ. Další příklad vyvolání členů ve vlastním scénáři vazby najdete v tématu Dynamické načítání a používání typů.
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
Poznámky
Tato metoda dynamicky vyvolá metodu reflektovanou touto instancí na obja předává spolu se zadanými parametry. Pokud je metoda statická, obj parametr je ignorován. Pro nestatické metody by měla být instance třídy, obj která dědí nebo deklaruje metodu a musí být stejného typu jako tato třída. Pokud metoda nemá žádné parametry, parameters hodnota by měla být null. V opačném případě musí být číslo, typ a pořadí prvků v parameters identické s číslem, typem a pořadím parametrů pro metodu, kterou tato instance odráží.
Nepovinný parametr nelze vynechat při voláních .Invoke Pokud chcete vyvolat metodu a vynechat volitelné parametry, volejte Type.InvokeMember místo toho.
Note
Pokud se toto přetížení metody používá k vyvolání konstruktoru instance, objekt zadaný pro obj je znovu inicializován; to znamená, že všechny inicializátory instance jsou provedeny. Vrácená hodnota je null. Pokud je vyvolán konstruktor třídy, třída je znovu inicializována; to znamená, že se spustí všechny inicializátory tříd. Vrácená hodnota je null.
U primitivních parametrů pass-by-value se provádí normální rozšíření (Například Int16 –> Int32). Pro parametry odkazu typu pass-by-value je povoleno normální rozšíření odkazu (odvozená třída na základní třídu a základní třída na typ rozhraní). U primitivních parametrů předávacího odkazu se však musí typy přesně shodovat. U parametrů referenčního odkazu typu pass-by-reference stále platí normální rozšíření.
Například pokud metoda reflektovaná touto instancí je deklarována jako public boolean Compare(String a, String b), pak parameters by měla být pole Objects s délkou 2 tak, aby parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2").
Pokud je parametr aktuální metody typ hodnoty a odpovídající argument je parametersnull, modul runtime předá instanci typu hodnoty inicializované nulou.
Reflexe používá dynamické vyhledávání metod při vyvolání virtuálních metod. Předpokládejme například, že třída B dědí z třídy A a obě implementují virtuální metodu s názvem M. Nyní předpokládejme, že máte MethodInfo objekt, který představuje M ve třídě A. Pokud použijete metodu Invoke k vyvolání M u objektu typu B, reflexe použije implementaci danou třídou B. I když je objekt typu B přetypován na A, použije se implementace daná třídou B (viz ukázka kódu níže).
Na druhou stranu, pokud metoda není virtuální, reflexe použije implementaci danou typem, ze kterého MethodInfo byl získán, bez ohledu na typ objektu předaného jako cíl.
Omezení přístupu se ignorují pro plně důvěryhodný kód. To znamená, že k soukromým konstruktorům, metodám, polím a vlastnostem lze přistupovat a vyvolat prostřednictvím reflexe, kdykoli je kód plně důvěryhodný.
Pokud vyvolaná metoda vyvolá výjimku, Exception.GetBaseException vrátí metoda původní výjimku.
Note
Tuto metodu lze použít pro přístup k neveřejným členům, pokud byl volající udělen ReflectionPermission příznakem ReflectionPermissionFlag.RestrictedMemberAccess a pokud je sada udělení nepřístupných členů omezena na sadu grantů volajícího nebo její podmnožinu. (Viz Aspekty zabezpečení reflexe.) Pokud chcete tuto funkci používat, měla by vaše aplikace cílit na .NET Framework 3.5 nebo novější.
Viz také
- InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])
- Dynamické načítání a používání typů