Delegate.CreateDelegate Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Crea un delegato del tipo specificato.
Overload
CreateDelegate(Type, Type, String, Boolean, Boolean) |
Crea un delegato del tipo specificato che rappresenta il metodo statico indicato della classe specificata, con la distinzione tra maiuscole e minuscole indicata e il funzionamento specificato in caso di errore di associazione. |
CreateDelegate(Type, Type, String, Boolean) |
Crea un delegato del tipo indicato che rappresenta il metodo statico specificato della classe indicata, con la distinzione tra maiuscole e minuscole specificata. |
CreateDelegate(Type, Object, String, Boolean) |
Crea un delegato del tipo specificato che rappresenta il metodo di istanza specificato, per il richiamo dell'istanza di classe specificata, con la distinzione tra maiuscole e minuscole specificata. |
CreateDelegate(Type, Object, MethodInfo, Boolean) |
Crea un delegato del tipo specificato che rappresenta il metodo statico o il metodo di istanza indicato, con il primo argomento specificato e il funzionamento indicato in caso di errore di associazione. |
CreateDelegate(Type, Object, String, Boolean, Boolean) |
Crea un delegato del tipo specificato che rappresenta il metodo di istanza specificato, per il richiamo dell'istanza di classe specificata, con la distinzione tra maiuscole e minuscole specificata e il funzionamento specificato in caso di errore di associazione. |
CreateDelegate(Type, MethodInfo, Boolean) |
Crea un delegato del tipo indicato per rappresentare il metodo statico specificato, in cui viene indicato anche il funzionamento in caso di errore di associazione. |
CreateDelegate(Type, Object, String) |
Crea un delegato del tipo specificato che rappresenta il metodo di istanza specificato per il richiamo dell'istanza di classe specificata. |
CreateDelegate(Type, Object, MethodInfo) |
Crea un delegato del tipo specificato che rappresenta il metodo statico o il metodo di istanza indicato, con il primo argomento specificato. |
CreateDelegate(Type, Type, String) |
Crea un delegato del tipo specificato che rappresenta il metodo statico specificato della classe specificata. |
CreateDelegate(Type, MethodInfo) |
Crea un delegato del tipo specificato per rappresentare il metodo specificato. |
CreateDelegate(Type, Type, String, Boolean, Boolean)
Crea un delegato del tipo specificato che rappresenta il metodo statico indicato della classe specificata, con la distinzione tra maiuscole e minuscole indicata e il funzionamento specificato in caso di errore di associazione.
public:
static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate? CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure);
static member CreateDelegate : Type * Type * string * bool * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Type, method As String, ignoreCase As Boolean, throwOnBindFailure As Boolean) As Delegate
Parametri
- method
- String
Nome del metodo statico che deve essere rappresentato dal delegato.
- ignoreCase
- Boolean
Valore booleano che indica se ignorare o meno la distinzione tra maiuscole e minuscole al momento di confrontare il nome del metodo.
- throwOnBindFailure
- Boolean
true
per generare un'eccezione se non è possibile associare method
. In caso contrario, false
.
Restituisce
Delegato del tipo specificato che rappresenta il metodo statico specificato della classe specificata.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
target
non è un oggetto RuntimeType
.
-oppure-
target
è un tipo generico aperto. Ciò significa che la proprietà ContainsGenericParameters è true
.
-oppure-
method
non è un metodo static
(metodo Shared
in Visual Basic).
-oppure-
Non è possibile associare method
, ad esempio perché non è stato trovato, e throwOnBindFailure
è true
.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Commenti
Questo metodo crea delegati solo per i metodi statici. Un metodo di istanza è un metodo associato a un'istanza di una classe; un metodo statico è un metodo associato alla classe stessa.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei metodi non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per la reflection.
Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.
Vedi anche
Si applica a
CreateDelegate(Type, Type, String, Boolean)
Crea un delegato del tipo indicato che rappresenta il metodo statico specificato della classe indicata, con la distinzione tra maiuscole e minuscole specificata.
public:
static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method, bool ignoreCase);
public static Delegate CreateDelegate (Type type, Type target, string method, bool ignoreCase);
static member CreateDelegate : Type * Type * string * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Type, method As String, ignoreCase As Boolean) As Delegate
Parametri
- method
- String
Nome del metodo statico che deve essere rappresentato dal delegato.
- ignoreCase
- Boolean
Valore booleano che indica se ignorare o meno la distinzione tra maiuscole e minuscole al momento di confrontare il nome del metodo.
Restituisce
Delegato del tipo specificato che rappresenta il metodo statico specificato della classe specificata.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
target
non è un oggetto RuntimeType
.
-oppure-
target
è un tipo generico aperto. Ciò significa che la proprietà ContainsGenericParameters è true
.
-oppure-
method
non è un metodo static
(metodo Shared
in Visual Basic).
-oppure-
Non possibile associare method
, ad esempio perché non è stato trovato.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Commenti
Questo metodo crea delegati solo per i metodi statici. Un metodo di istanza è un metodo associato a un'istanza di una classe; un metodo statico è un metodo associato alla classe stessa.
Questo overload del metodo equivale a chiamare l'overload del CreateDelegate(Type, Type, String, Boolean, Boolean) metodo, specificando true
per throwOnBindFailure
.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei metodi non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per la reflection.
Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.
Vedi anche
Si applica a
CreateDelegate(Type, Object, String, Boolean)
Crea un delegato del tipo specificato che rappresenta il metodo di istanza specificato, per il richiamo dell'istanza di classe specificata, con la distinzione tra maiuscole e minuscole specificata.
public:
static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method, bool ignoreCase);
public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase);
static member CreateDelegate : Type * obj * string * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Object, method As String, ignoreCase As Boolean) As Delegate
Parametri
- target
- Object
Istanza di classe per la quale viene richiamato method
.
- method
- String
Nome del metodo di istanza che deve essere rappresentato dal delegato.
- ignoreCase
- Boolean
Valore booleano che indica se ignorare o meno la distinzione tra maiuscole e minuscole al momento di confrontare il nome del metodo.
Restituisce
Delegato del tipo specificato che rappresenta il metodo di istanza specificato per il richiamo dell'istanza di classe specificata.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
method
non è un metodo di istanza.
-oppure-
Non possibile associare method
, ad esempio perché non è stato trovato.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Commenti
Questo metodo crea delegati solo per i metodi di istanza. Un metodo di istanza è un metodo associato a un'istanza di una classe; un metodo statico è un metodo associato alla classe stessa.
Questo overload di metodo equivale a chiamare l'overload del CreateDelegate(Type, Object, String, Boolean, Boolean) metodo, specificando true
per throwOnBindFailure
.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessione dei metodi non pubblici è limitato al set di concessione del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per Reflection.
Per usare questa funzionalità, l'applicazione deve essere destinato a .NET Framework 3.5 o versione successiva.
Vedi anche
Si applica a
CreateDelegate(Type, Object, MethodInfo, Boolean)
Crea un delegato del tipo specificato che rappresenta il metodo statico o il metodo di istanza indicato, con il primo argomento specificato e il funzionamento indicato in caso di errore di associazione.
public:
static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ firstArgument, System::Reflection::MethodInfo ^ method, bool throwOnBindFailure);
public static Delegate? CreateDelegate (Type type, object? firstArgument, System.Reflection.MethodInfo method, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, object firstArgument, System.Reflection.MethodInfo method, bool throwOnBindFailure);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, firstArgument As Object, method As MethodInfo, throwOnBindFailure As Boolean) As Delegate
Parametri
- firstArgument
- Object
Object che rappresenta il primo argomento del metodo rappresentato dal delegato. Per i metodi di istanza, tale oggetto deve essere compatibile con il tipo di istanza.
- method
- MethodInfo
MethodInfo che descrive il metodo statico o il metodo di istanza che deve essere rappresentato dal delegato.
- throwOnBindFailure
- Boolean
true
per generare un'eccezione se non è possibile associare method
. In caso contrario, false
.
Restituisce
Delegato del tipo specificato che rappresenta il metodo statico o di istanza specificato oppure null
se throwOnBindFailure
è false
e non è possibile associare il delegato a method
.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
method
non può essere associato e throwOnBindFailure
è true
.
-oppure-
method
non è un oggetto RuntimeMethodInfo
. Vedere Tipi di runtime nella reflection.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Esempio
Questa sezione contiene tre esempi di codice. Il primo esempio illustra i quattro tipi di delegati che possono essere creati: chiuso su un metodo di istanza, aperto su un metodo di istanza, aperto su un metodo statico e chiuso su un metodo statico.
Il secondo esempio di codice illustra i tipi di parametri compatibili e i tipi restituiti.
Il terzo esempio di codice definisce un singolo tipo delegato e mostra tutti i metodi che il tipo delegato può rappresentare.
Esempio 1
Nell'esempio di codice seguente vengono illustrati i quattro modi in cui è possibile creare un delegato usando questo overload del CreateDelegate metodo.
Nota
Esistono due overload del metodo che specificano firstArgument
e un MethodInfo. La loro funzionalità è la stessa, ad eccezione del CreateDelegate fatto che quella consente di specificare se generare un errore di associazione e l'altra genera sempre. Questo esempio di codice usa entrambi gli overload.
L'esempio dichiara una classe C
con un metodo statico e un metodo M1
M2
di istanza e tre tipi di delegato: D1
accetta un'istanza di C
e una stringa, D2
accetta una stringa e D3
non ha argomenti.
Una seconda classe denominata Example
contiene il codice che crea i delegati.
Viene creato un delegato di tipo
D2
, chiuso su un'istanza diC
, per il metodoM1
di istanza . Viene richiamato con stringhe diverse, per mostrare che l'istanza associata diC
viene sempre usata.Viene creato un delegato di tipo
D1
, che rappresenta un metodo di istanza aperto, per il metodoM1
di istanza . Quando viene richiamato il delegato, è necessario passare un'istanza.Viene creato un delegato di tipo
D2
, che rappresenta un metodo statico aperto, per il metodoM2
statico .Infine, un delegato di tipo
D3
, chiuso su una stringa, viene creato per il metodoM2
statico . Il metodo viene richiamato per mostrare che usa la stringa associata.
using System;
using System.Reflection;
using System.Security.Permissions;
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();
// A sample class with an instance method and a static method.
//
public class C
{
private int id;
public C(int id) { this.id = id; }
public void M1(string s)
{
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}",
this.id, s);
}
public static void M2(string s)
{
Console.WriteLine("Static method M2 on C: s = {0}", s);
}
}
public class Example
{
public static void Main()
{
C c1 = new C(42);
// Get a MethodInfo for each method.
//
MethodInfo mi1 = typeof(C).GetMethod("M1",
BindingFlags.Public | BindingFlags.Instance);
MethodInfo mi2 = typeof(C).GetMethod("M2",
BindingFlags.Public | BindingFlags.Static);
D1 d1;
D2 d2;
D3 d3;
Console.WriteLine("\nAn instance method closed over C.");
// In this case, the delegate and the
// method must have the same list of argument types; use
// delegate type D2 with instance method M1.
//
Delegate test =
Delegate.CreateDelegate(typeof(D2), c1, mi1, false);
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
//
if (test != null)
{
d2 = (D2) test;
// The same instance of C is used every time the
// delegate is invoked.
d2("Hello, World!");
d2("Hi, Mom!");
}
Console.WriteLine("\nAn open instance method.");
// In this case, the delegate has one more
// argument than the instance method; this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
//
d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);
// An instance of C must be passed in each time the
// delegate is invoked.
//
d1(c1, "Hello, World!");
d1(new C(5280), "Hi, Mom!");
Console.WriteLine("\nAn open static method.");
// In this case, the delegate and the method must
// have the same list of argument types; use delegate type
// D2 with static method M2.
//
d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);
// No instances of C are involved, because this is a static
// method.
//
d2("Hello, World!");
d2("Hi, Mom!");
Console.WriteLine("\nA static method closed over the first argument (String).");
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
//
d3 = (D3) Delegate.CreateDelegate(typeof(D3),
"Hello, World!", mi2);
// Each time the delegate is invoked, the same string is
// used.
d3();
}
}
/* This code example produces the following output:
An instance method closed over C.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 42, s = Hi, Mom!
An open instance method.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 5280, s = Hi, Mom!
An open static method.
Static method M2 on C: s = Hello, World!
Static method M2 on C: s = Hi, Mom!
A static method closed over the first argument (String).
Static method M2 on C: s = Hello, World!
*/
open System
open System.Reflection
// A sample class with an instance method and a static method.
type C(id) =
member _.M1(s) =
printfn $"Instance method M1 on C: id = %i{id}, s = %s{s}"
static member M2(s) =
printfn $"Static method M2 on C: s = %s{s}"
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit
let c1 = C 42
// Get a MethodInfo for each method.
//
let mi1 = typeof<C>.GetMethod("M1", BindingFlags.Public ||| BindingFlags.Instance)
let mi2 = typeof<C>.GetMethod("M2", BindingFlags.Public ||| BindingFlags.Static)
printfn "\nAn instance method closed over C."
// In this case, the delegate and the
// method must have the same list of argument types use
// delegate type D2 with instance method M1.
let test = Delegate.CreateDelegate(typeof<D2>, c1, mi1, false)
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
if test <> null then
let d2 = test :?> D2
// The same instance of C is used every time the
// delegate is invoked.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nAn open instance method."
// In this case, the delegate has one more
// argument than the instance method this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1
// An instance of C must be passed in each time the
// delegate is invoked.
d1.Invoke(c1, "Hello, World!")
d1.Invoke(C 5280, "Hi, Mom!")
printfn "\nAn open static method."
// In this case, the delegate and the method must
// have the same list of argument types use delegate type
// D2 with static method M2.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2
// No instances of C are involved, because this is a static
// method.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nA static method closed over the first argument (String)."
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3
// Each time the delegate is invoked, the same string is used.
d3.Invoke()
// This code example produces the following output:
// An instance method closed over C.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 42, s = Hi, Mom!
//
// An open instance method.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 5280, s = Hi, Mom!
//
// An open static method.
// Static method M2 on C: s = Hello, World!
// Static method M2 on C: s = Hi, Mom!
//
// A static method closed over the first argument (String).
// Static method M2 on C: s = Hello, World!
Imports System.Reflection
Imports System.Security.Permissions
' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String)
Public Delegate Sub D2(ByVal s As String)
Public Delegate Sub D3()
' A sample class with an instance method and a Shared method.
'
Public Class C
Private id As Integer
Public Sub New(ByVal id As Integer)
Me.id = id
End Sub
Public Sub M1(ByVal s As String)
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}", _
Me.id, s)
End Sub
Public Shared Sub M2(ByVal s As String)
Console.WriteLine("Shared method M2 on C: s = {0}", s)
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim c1 As New C(42)
' Get a MethodInfo for each method.
'
Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
BindingFlags.Public Or BindingFlags.Instance)
Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
BindingFlags.Public Or BindingFlags.Static)
Dim d1 As D1
Dim d2 As D2
Dim d3 As D3
Console.WriteLine(vbLf & "An instance method closed over C.")
' In this case, the delegate and the
' method must have the same list of argument types; use
' delegate type D2 with instance method M1.
'
Dim test As [Delegate] = _
[Delegate].CreateDelegate(GetType(D2), c1, mi1, False)
' Because False was specified for throwOnBindFailure
' in the call to CreateDelegate, the variable 'test'
' contains Nothing if the method fails to bind (for
' example, if mi1 happened to represent a method of
' some class other than C).
'
If test IsNot Nothing Then
d2 = CType(test, D2)
' The same instance of C is used every time the
' delegate is invoked.
d2("Hello, World!")
d2("Hi, Mom!")
End If
Console.WriteLine(vbLf & "An open instance method.")
' In this case, the delegate has one more
' argument than the instance method; this argument comes
' at the beginning, and represents the hidden instance
' argument of the instance method. Use delegate type D1
' with instance method M1.
'
d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
' An instance of C must be passed in each time the
' delegate is invoked.
'
d1(c1, "Hello, World!")
d1(New C(5280), "Hi, Mom!")
Console.WriteLine(vbLf & "An open Shared method.")
' In this case, the delegate and the method must
' have the same list of argument types; use delegate type
' D2 with Shared method M2.
'
d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
' No instances of C are involved, because this is a Shared
' method.
'
d2("Hello, World!")
d2("Hi, Mom!")
Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
' The delegate must omit the first argument of the method.
' A string is passed as the firstArgument parameter, and
' the delegate is bound to this string. Use delegate type
' D3 with Shared method M2.
'
d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
' Each time the delegate is invoked, the same string is
' used.
d3()
End Sub
End Class
' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C: s = Hello, World!
'Shared method M2 on C: s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C: s = Hello, World!
'
Esempio 2
Nell'esempio di codice seguente viene illustrata la compatibilità dei tipi di parametri e dei tipi restituiti.
Nota
Questo esempio di codice usa l'overload del CreateDelegate(Type, MethodInfo) metodo. L'uso di altri overload che accettano MethodInfo è simile.
L'esempio di codice definisce una classe di base denominata Base
e una classe denominata Derived
che deriva da Base
. La classe derivata ha un static
metodo (Shared
in Visual Basic) denominato MyMethod
con un parametro di tipo Base
e un tipo restituito di Derived
. L'esempio di codice definisce anche un delegato denominato Example
con un parametro di tipo Derived
e un tipo restituito di Base
.
Nell'esempio di codice viene illustrato che il delegato denominato Example
può essere usato per rappresentare il metodo MyMethod
. Il metodo può essere associato al delegato perché:
Il tipo di parametro del delegato () è più restrittivo del tipo
MyMethod
di parametro (Base
Derived
), in modo che sia sempre sicuro passare l'argomento del delegato aMyMethod
.Il tipo restituito di
MyMethod
(Derived
) è più restrittivo del tipo di parametro del delegato (Base
), in modo che sia sempre sicuro eseguire il cast del tipo restituito del metodo al tipo restituito del delegato.
L'esempio di codice non produce alcun output.
using namespace System;
using namespace System::Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public ref class Base {};
public ref class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public:
static Derived^ MyMethod(Base^ arg)
{
Base^ dummy = arg;
return gcnew Derived();
}
};
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);
void main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags::Public | BindingFlags::Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example^ ex =
(Example^) Delegate::CreateDelegate(Example::typeid, minfo);
// Execute MyMethod using the delegate Example.
//
Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public class Base {}
public class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public static Derived MyMethod(Base arg)
{
Base dummy = arg;
return new Derived();
}
}
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);
class Test
{
public static void Main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example ex =
(Example) Delegate.CreateDelegate(typeof(Example), minfo);
// Execute MyMethod using the delegate Example.
//
Base b = ex(new Derived());
}
}
open System
open System.Reflection
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end
type Derived() =
inherit Base()
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
static member MyMethod(arg: Base) =
Derived()
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base
// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static
// Get a MethodInfo that represents MyMethod.
let minfo = typeof<Derived>.GetMethod("MyMethod", flags)
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example
// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
Imports System.Reflection
' Define two classes to use in the demonstration, a base class and
' a class that derives from it.
'
Public Class Base
End Class
Public Class Derived
Inherits Base
' Define a Shared method to use in the demonstration. The method
' takes an instance of Base and returns an instance of Derived.
' For the purposes of the demonstration, it is not necessary for
' the method to do anything useful.
'
Public Shared Function MyMethod(ByVal arg As Base) As Derived
Dim dummy As Base = arg
Return New Derived()
End Function
End Class
' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base
Module Test
Sub Main()
' The binding flags needed to retrieve MyMethod.
Dim flags As BindingFlags = _
BindingFlags.Public Or BindingFlags.Static
' Get a MethodInfo that represents MyMethod.
Dim minfo As MethodInfo = _
GetType(Derived).GetMethod("MyMethod", flags)
' Demonstrate contravariance of parameter types and covariance
' of return types by using the delegate Example to represent
' MyMethod. The delegate binds to the method because the
' parameter of the delegate is more restrictive than the
' parameter of the method (that is, the delegate accepts an
' instance of Derived, which can always be safely passed to
' a parameter of type Base), and the return type of MyMethod
' is more restrictive than the return type of Example (that
' is, the method returns an instance of Derived, which can
' always be safely cast to type Base).
'
Dim ex As Example = CType( _
[Delegate].CreateDelegate(GetType(Example), minfo), _
Example _
)
' Execute MyMethod using the delegate Example.
'
Dim b As Base = ex(New Derived())
End Sub
End Module
Esempio 3
Nell'esempio di codice seguente vengono illustrati tutti i metodi che possono rappresentare un singolo tipo delegato.
Nota
Esistono due overload del metodo che specificano firstArgument
e un MethodInfo. La loro funzionalità è la stessa, ad eccezione del CreateDelegate fatto che quella consente di specificare se generare un errore di associazione e l'altra genera sempre. Questo esempio di codice usa entrambi gli overload.
L'esempio di codice definisce due classi C
e F
e un tipo D
delegato con un argomento di tipo C
. Le classi hanno metodi M1
statici e di istanza corrispondenti, M3
e M4
C
hanno anche un metodo M2
di istanza senza argomenti.
Una terza classe denominata Example
contiene il codice che crea i delegati.
I delegati vengono creati per il metodo
M1
di istanza di tipoC
e tipoF
. Ogni viene chiuso su un'istanza del rispettivo tipo. Il metodoM1
di tipoC
visualizza leID
proprietà dell'istanza associata e dell'argomento.Viene creato un delegato per il metodo
M2
di tipoC
. Si tratta di un delegato di istanza aperta, in cui l'argomento del delegato rappresenta il primo argomento nascosto nel metodo dell'istanza. Il metodo non ha altri argomenti.I delegati vengono creati per il metodo
M3
statico di tipoC
e tipoF
. Questi sono delegati statici aperti.Infine, i delegati vengono creati per il metodo statico di tipo
C
eF
tipo. Ogni metodoM4
ha il tipo dichiarante come primo argomento e viene fornita un'istanza del tipo, pertanto i delegati vengono chiusi sui primi argomenti. Il metodoM4
di tipoC
visualizza leID
proprietà dell'istanza associata e dell'argomento.
using System;
using System.Reflection;
using System.Security.Permissions;
// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
//
public delegate void D(C c);
// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
//
public class C
{
private int id;
public int ID { get { return id; }}
public C(int id) { this.id = id; }
public void M1(C c)
{
Console.WriteLine("Instance method M1(C c) on C: this.id = {0}, c.ID = {1}",
this.id, c.ID);
}
public void M2()
{
Console.WriteLine("Instance method M2() on C: this.id = {0}",
this.id);
}
public static void M3(C c)
{
Console.WriteLine("Static method M3(C c) on C: c.ID = {0}", c.ID);
}
public static void M4(C c1, C c2)
{
Console.WriteLine("Static method M4(C c1, C c2) on C: c1.ID = {0}, c2.ID = {1}",
c1.ID, c2.ID);
}
}
public class F
{
public void M1(C c)
{
Console.WriteLine("Instance method M1(C c) on F: c.ID = {0}",
c.ID);
}
public static void M3(C c)
{
Console.WriteLine("Static method M3(C c) on F: c.ID = {0}", c.ID);
}
public static void M4(F f, C c)
{
Console.WriteLine("Static method M4(F f, C c) on F: c.ID = {0}",
c.ID);
}
}
public class Example
{
public static void Main()
{
C c1 = new C(42);
C c2 = new C(1491);
F f1 = new F();
D d;
// Instance method with one argument of type C.
MethodInfo cmi1 = typeof(C).GetMethod("M1");
// Instance method with no arguments.
MethodInfo cmi2 = typeof(C).GetMethod("M2");
// Static method with one argument of type C.
MethodInfo cmi3 = typeof(C).GetMethod("M3");
// Static method with two arguments of type C.
MethodInfo cmi4 = typeof(C).GetMethod("M4");
// Instance method with one argument of type C.
MethodInfo fmi1 = typeof(F).GetMethod("M1");
// Static method with one argument of type C.
MethodInfo fmi3 = typeof(F).GetMethod("M3");
// Static method with an argument of type F and an argument
// of type C.
MethodInfo fmi4 = typeof(F).GetMethod("M4");
Console.WriteLine("\nAn instance method on any type, with an argument of type C.");
// D can represent any instance method that exactly matches its
// signature. Methods on C and F are shown here.
//
d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi1);
d(c2);
d = (D) Delegate.CreateDelegate(typeof(D), f1, fmi1);
d(c2);
Console.WriteLine("\nAn instance method on C with no arguments.");
// D can represent an instance method on C that has no arguments;
// in this case, the argument of D represents the hidden first
// argument of any instance method. The delegate acts like a
// static method, and an instance of C must be passed each time
// it is invoked.
//
d = (D) Delegate.CreateDelegate(typeof(D), null, cmi2);
d(c1);
Console.WriteLine("\nA static method on any type, with an argument of type C.");
// D can represent any static method with the same signature.
// Methods on F and C are shown here.
//
d = (D) Delegate.CreateDelegate(typeof(D), null, cmi3);
d(c1);
d = (D) Delegate.CreateDelegate(typeof(D), null, fmi3);
d(c1);
Console.WriteLine("\nA static method on any type, with an argument of");
Console.WriteLine(" that type and an argument of type C.");
// D can represent any static method with one argument of the
// type the method belongs and a second argument of type C.
// In this case, the method is closed over the instance of
// supplied for the its first argument, and acts like an instance
// method. Methods on F and C are shown here.
//
d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi4);
d(c2);
Delegate test =
Delegate.CreateDelegate(typeof(D), f1, fmi4, false);
// This final example specifies false for throwOnBindFailure
// in the call to CreateDelegate, so the variable 'test'
// contains Nothing if the method fails to bind (for
// example, if fmi4 happened to represent a method of
// some class other than F).
//
if (test != null)
{
d = (D) test;
d(c2);
}
}
}
/* This code example produces the following output:
An instance method on any type, with an argument of type C.
Instance method M1(C c) on C: this.id = 42, c.ID = 1491
Instance method M1(C c) on F: c.ID = 1491
An instance method on C with no arguments.
Instance method M2() on C: this.id = 42
A static method on any type, with an argument of type C.
Static method M3(C c) on C: c.ID = 42
Static method M3(C c) on F: c.ID = 42
A static method on any type, with an argument of
that type and an argument of type C.
Static method M4(C c1, C c2) on C: c1.ID = 42, c2.ID = 1491
Static method M4(F f, C c) on F: c.ID = 1491
*/
open System
// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
type C(id) =
member _.ID = id
member _.M1(c: C) =
printfn $"Instance method M1(C c) on C: this.id = {id}, c.ID = {c.ID}"
member _.M2() =
printfn $"Instance method M2() on C: this.id = {id}"
static member M3(c: C) =
printfn $"Static method M3(C c) on C: c.ID = {c.ID}"
static member M4(c1: C, c2: C) =
printfn $"Static method M4(C c1, C c2) on C: c1.ID = {c1.ID}, c2.ID = {c2.ID}"
// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
type D = delegate of C -> unit
type F() =
member _.M1(c: C) =
printfn $"Instance method M1(C c) on F: c.ID = {c.ID}"
member _.M3(c: C) =
printfn $"Static method M3(C c) on F: c.ID = {c.ID}"
member _.M4(f: F, c: C) =
printfn $"Static method M4(F f, C c) on F: c.ID = {c.ID}"
[<EntryPoint>]
let main _ =
let c1 = C 42
let c2 = C 1491
let f1 = F()
// Instance method with one argument of type C.
let cmi1 = typeof<C>.GetMethod "M1"
// Instance method with no arguments.
let cmi2 = typeof<C>.GetMethod "M2"
// Static method with one argument of type C.
let cmi3 = typeof<C>.GetMethod "M3"
// Static method with two arguments of type C.
let cmi4 = typeof<C>.GetMethod "M4"
// Instance method with one argument of type C.
let fmi1 = typeof<F>.GetMethod "M1"
// Static method with one argument of type C.
let fmi3 = typeof<F>.GetMethod "M3"
// Static method with an argument of type F and an argument
// of type C.
let fmi4 = typeof<F>.GetMethod "M4"
printfn "\nAn instance method on any type, with an argument of type C."
// D can represent any instance method that exactly matches its
// signature. Methods on C and F are shown here.
let d = Delegate.CreateDelegate(typeof<D>, c1, cmi1) :?> D
d.Invoke c2
let d = Delegate.CreateDelegate(typeof<D>, f1, fmi1) :?> D
d.Invoke c2
Console.WriteLine("\nAn instance method on C with no arguments.")
// D can represent an instance method on C that has no arguments
// in this case, the argument of D represents the hidden first
// argument of any instance method. The delegate acts like a
// static method, and an instance of C must be passed each time
// it is invoked.
let d = Delegate.CreateDelegate(typeof<D>, null, cmi2) :?> D
d.Invoke c1
printfn "\nA static method on any type, with an argument of type C."
// D can represent any static method with the same signature.
// Methods on F and C are shown here.
let d = Delegate.CreateDelegate(typeof<D>, null, cmi3) :?> D
d.Invoke c1
let d = Delegate.CreateDelegate(typeof<D>, null, fmi3) :?> D
d.Invoke c1
printfn "\nA static method on any type, with an argument of"
printfn " that type and an argument of type C."
// D can represent any static method with one argument of the
// type the method belongs and a second argument of type C.
// In this case, the method is closed over the instance of
// supplied for the its first argument, and acts like an instance
// method. Methods on F and C are shown here.
let d = Delegate.CreateDelegate(typeof<D>, c1, cmi4) :?> D
d.Invoke c2
let test =
Delegate.CreateDelegate(typeof<D>, f1, fmi4, false)
// This final example specifies false for throwOnBindFailure
// in the call to CreateDelegate, so the variable 'test'
// contains Nothing if the method fails to bind (for
// example, if fmi4 happened to represent a method of
// some class other than F).
match test with
| :? D as d ->
d.Invoke c2
| _ -> ()
0
// This code example produces the following output:
// An instance method on any type, with an argument of type C.
// Instance method M1(C c) on C: this.id = 42, c.ID = 1491
// Instance method M1(C c) on F: c.ID = 1491
//
// An instance method on C with no arguments.
// Instance method M2() on C: this.id = 42
//
// A static method on any type, with an argument of type C.
// Static method M3(C c) on C: c.ID = 42
// Static method M3(C c) on F: c.ID = 42
//
// A static method on any type, with an argument of
// that type and an argument of type C.
// Static method M4(C c1, C c2) on C: c1.ID = 42, c2.ID = 1491
// Static method M4(F f, C c) on F: c.ID = 1491
Imports System.Reflection
Imports System.Security.Permissions
' Declare a delegate type. The object of this code example
' is to show all the methods this delegate can bind to.
'
Public Delegate Sub D(ByVal c As C)
' Declare two sample classes, C and F. Class C has an ID
' property so instances can be identified.
'
Public Class C
Private _id As Integer
Public ReadOnly Property ID() As Integer
Get
Return _id
End Get
End Property
Public Sub New(ByVal newId As Integer)
Me._id = newId
End Sub
Public Sub M1(ByVal c As C)
Console.WriteLine("Instance method M1(c As C) on C: this.id = {0}, c.ID = {1}", _
Me.id, c.ID)
End Sub
Public Sub M2()
Console.WriteLine("Instance method M2() on C: this.id = {0}", Me.id)
End Sub
Public Shared Sub M3(ByVal c As C)
Console.WriteLine("Shared method M3(c As C) on C: c.ID = {0}", c.ID)
End Sub
Public Shared Sub M4(ByVal c1 As C, ByVal c2 As C)
Console.WriteLine("Shared method M4(c1 As C, c2 As C) on C: c1.ID = {0}, c2.ID = {1}", _
c1.ID, c2.ID)
End Sub
End Class
Public Class F
Public Sub M1(ByVal c As C)
Console.WriteLine("Instance method M1(c As C) on F: c.ID = {0}", c.ID)
End Sub
Public Shared Sub M3(ByVal c As C)
Console.WriteLine("Shared method M3(c As C) on F: c.ID = {0}", c.ID)
End Sub
Public Shared Sub M4(ByVal f As F, ByVal c As C)
Console.WriteLine("Shared method M4(f As F, c As C) on F: c.ID = {0}", c.ID)
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim c1 As New C(42)
Dim c2 As New C(1491)
Dim f1 As New F()
Dim d As D
' Instance method with one argument of type C.
Dim cmi1 As MethodInfo = GetType(C).GetMethod("M1")
' Instance method with no arguments.
Dim cmi2 As MethodInfo = GetType(C).GetMethod("M2")
' Shared method with one argument of type C.
Dim cmi3 As MethodInfo = GetType(C).GetMethod("M3")
' Shared method with two arguments of type C.
Dim cmi4 As MethodInfo = GetType(C).GetMethod("M4")
' Instance method with one argument of type C.
Dim fmi1 As MethodInfo = GetType(F).GetMethod("M1")
' Shared method with one argument of type C.
Dim fmi3 As MethodInfo = GetType(F).GetMethod("M3")
' Shared method with an argument of type F and an
' argument of type C.
Dim fmi4 As MethodInfo = GetType(F).GetMethod("M4")
Console.WriteLine(vbLf & "An instance method on any type, with an argument of type C.")
' D can represent any instance method that exactly matches its
' signature. Methods on C and F are shown here.
'
d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi1), D)
d(c2)
d = CType([Delegate].CreateDelegate(GetType(D), f1, fmi1), D)
d(c2)
Console.WriteLine(vbLf & "An instance method on C with no arguments.")
' D can represent an instance method on C that has no arguments;
' in this case, the argument of D represents the hidden first
' argument of any instance method. The delegate acts like a
' Shared method, and an instance of C must be passed each time
' it is invoked.
'
d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi2), D)
d(c1)
Console.WriteLine(vbLf & "A Shared method on any type, with an argument of type C.")
' D can represent any Shared method with the same signature.
' Methods on F and C are shown here.
'
d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi3), D)
d(c1)
d = CType([Delegate].CreateDelegate(GetType(D), Nothing, fmi3), D)
d(c1)
Console.WriteLine(vbLf & "A Shared method on any type, with an argument of")
Console.WriteLine(" that type and an argument of type C.")
' D can represent any Shared method with one argument of the
' type the method belongs and a second argument of type C.
' In this case, the method is closed over the instance of
' supplied for the its first argument, and acts like an instance
' method. Methods on F and C are shown here.
'
d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi4), D)
d(c2)
Dim test As [Delegate] = _
[Delegate].CreateDelegate(GetType(D), f1, fmi4, false)
' This final example specifies False for throwOnBindFailure
' in the call to CreateDelegate, so the variable 'test'
' contains Nothing if the method fails to bind (for
' example, if fmi4 happened to represent a method of
' some class other than F).
'
If test IsNot Nothing Then
d = CType(test, D)
d(c2)
End If
End Sub
End Class
' This code example produces the following output:
'
'An instance method on any type, with an argument of type C.
'Instance method M1(c As C) on C: this.id = 42, c.ID = 1491
'Instance method M1(c As C) on F: c.ID = 1491
'
'An instance method on C with no arguments.
'Instance method M2() on C: this.id = 42
'
'A Shared method on any type, with an argument of type C.
'Shared method M3(c As C) on C: c.ID = 42
'Shared method M3(c As C) on F: c.ID = 42
'
'A Shared method on any type, with an argument of
' that type and an argument of type C.
'Shared method M4(c1 As C, c2 As C) on C: c1.ID = 42, c2.ID = 1491
'Shared method M4(f As F, c As C) on F: c.ID = 1491
'
Commenti
Questo overload del metodo e l'overload del CreateDelegate(Type, Object, MethodInfo) metodo, che genera sempre un errore di associazione, fornisce il modo più flessibile per creare delegati. È possibile usarli per creare delegati per metodi statici o di istanza, con o senza un primo argomento.
Nota
Se non si specifica un primo argomento, usare l'overload del CreateDelegate(Type, MethodInfo, Boolean) metodo per migliorare le prestazioni.
Il tipo delegato e il metodo devono avere tipi restituiti compatibili. Ovvero, il tipo restituito di method
deve essere assegnabile al tipo restituito di type
.
Se firstArgument
viene specificato, viene passato a method
ogni volta che viene richiamato il delegato. firstArgument
Viene detto che deve essere associato al delegato e il delegato viene detto chiuso sul primo argomento. Se method
è (Shared
in Visual Basic), l'elenco di argomenti fornito quando richiama il delegato include tutti i parametri tranne il primo; se method
è static
un metodo di istanza, viene firstArgument
passato al parametro dell'istanza nascosta (rappresentato da this
in C#o da Me
in Visual Basic).
Se firstArgument
viene specificato, il primo parametro di deve essere un tipo di method
riferimento e firstArgument
deve essere compatibile con tale tipo.
Importante
Se method
è static
(Shared
in Visual Basic) e il primo parametro è di tipo Object o ValueType, può firstArgument
essere un tipo di valore. In questo caso firstArgument
viene automaticamente casellata. La casella automatica non si verifica per altri argomenti, perché in una chiamata di funzione C# o Visual Basic.
Se firstArgument
è un riferimento Null ed method
è un metodo di istanza, il risultato dipende dalle firme del tipo type
delegato e da method
:
Se la firma di
type
include in modo esplicito il primo parametro nascosto di , il delegato viene detto di rappresentare un metodo dimethod
istanza aperta. Quando viene richiamato il delegato, il primo argomento nell'elenco di argomenti viene passato al parametro di istanza nascosto dimethod
.Se le firme di e
type
corrispondono ,ovvero tutti i tipi dimethod
parametri sono compatibili, il delegato viene detto chiuso su un riferimento Null. Richiamare il delegato è come chiamare un metodo di istanza su un'istanza Null, che non è una cosa particolarmente utile da eseguire.
Se firstArgument
è un riferimento Null ed method
è statico, il risultato dipende dalle firme del tipo type
delegato e di method
:
Se la firma e
method
type
la corrispondenza ,ovvero tutti i tipi di parametro sono compatibili, il delegato viene detto di rappresentare un metodo statico aperto. Questo è il caso più comune per i metodi statici. In questo caso, è possibile ottenere prestazioni leggermente migliori usando l'overload del CreateDelegate(Type, MethodInfo, Boolean) metodo .Se la firma di
type
inizia con il secondo parametro dimethod
e il resto dei tipi di parametro sono compatibili, il delegato viene detto chiuso su un riferimento Null. Quando viene richiamato il delegato, viene passato un riferimento Null al primo parametro dimethod
.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei metodi non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per la reflection.
Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.
Tipi di parametri compatibili e tipo restituito
I tipi di parametro e il tipo restituito di un delegato devono essere compatibili con i tipi di parametro e il tipo restituito del metodo rappresentato dal delegato; i tipi non devono corrispondere esattamente.
Un parametro di un delegato è compatibile con il parametro di un metodo corrispondente se il tipo del parametro del delegato è più restrittivo rispetto al tipo del parametro del metodo. In questo modo si garantisce che un argomento passato al delegato possa essere passato in modo sicuro al metodo.
Analogamente, il tipo restituito di un delegato è compatibile con il tipo restituito di un metodo se il tipo restituito del metodo è più restrittivo rispetto al tipo restituito del delegato. In questo modo si garantisce la possibilità di eseguire in modo sicuro il cast del valore restituito del metodo nel tipo restituito del delegato.
Ad esempio, un delegato con un parametro di tipo Hashtable e un tipo restituito di Object può rappresentare un metodo con un parametro di tipo Object e un valore restituito di tipo Hashtable.
Determinazione dei metodi che un delegato può rappresentare
Un altro modo utile per considerare la flessibilità fornita da questo overload di CreateDelegate è che qualsiasi delegato specificato può rappresentare quattro diverse combinazioni di firma del metodo e tipo di metodo (statico rispetto all'istanza). Si consideri un tipo D
delegato con un argomento di tipo C
. Di seguito vengono descritti i metodi D
che possono rappresentare, ignorando il tipo restituito perché deve corrispondere in tutti i casi:
D
può rappresentare qualsiasi metodo di istanza con esattamente un argomento di tipoC
, indipendentemente dal tipo a cui appartiene il metodo di istanza. Quando CreateDelegate viene chiamato,firstArgument
è un'istanza del tipomethod
a cui appartiene e si dice che il delegato risultante venga chiuso su tale istanza. (Trivially,D
può anche essere chiuso su un riferimento Null sefirstArgument
ènull
. )D
può rappresentare un metodo di istanza diC
senza argomenti. Quando CreateDelegate viene chiamato,firstArgument
è un riferimento Null. Il delegato risultante rappresenta un metodo di istanza aperto e un'istanza diC
deve essere fornita ogni volta che viene richiamata.D
può rappresentare un metodo statico che accetta un argomento di tipoC
e tale metodo può appartenere a qualsiasi tipo. Quando CreateDelegate viene chiamato,firstArgument
è un riferimento Null. Il delegato risultante rappresenta un metodo statico aperto e un'istanza diC
deve essere fornita ogni volta che viene richiamata.D
può rappresentare un metodo statico che appartiene al tipoF
e ha due argomenti, di tipoF
e di tipoC
. Quando CreateDelegate viene chiamato ,firstArgument
è un'istanza diF
. Il delegato risultante rappresenta un metodo statico chiuso su tale istanza diF
. Si noti che nel caso in cuiF
eC
siano dello stesso tipo, il metodo statico ha due argomenti di quel tipo. In questo caso,D
viene chiuso su un riferimento Null sefirstArgument
ènull
.
Vedi anche
Si applica a
CreateDelegate(Type, Object, String, Boolean, Boolean)
Crea un delegato del tipo specificato che rappresenta il metodo di istanza specificato, per il richiamo dell'istanza di classe specificata, con la distinzione tra maiuscole e minuscole specificata e il funzionamento specificato in caso di errore di associazione.
public:
static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate? CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure);
static member CreateDelegate : Type * obj * string * bool * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Object, method As String, ignoreCase As Boolean, throwOnBindFailure As Boolean) As Delegate
Parametri
- target
- Object
Istanza di classe per la quale viene richiamato method
.
- method
- String
Nome del metodo di istanza che deve essere rappresentato dal delegato.
- ignoreCase
- Boolean
Valore booleano che indica se ignorare o meno la distinzione tra maiuscole e minuscole al momento di confrontare il nome del metodo.
- throwOnBindFailure
- Boolean
true
per generare un'eccezione se non è possibile associare method
. In caso contrario, false
.
Restituisce
Delegato del tipo specificato che rappresenta il metodo di istanza specificato per il richiamo dell'istanza di classe specificata.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
method
non è un metodo di istanza.
-oppure-
Non è possibile associare method
, ad esempio perché non è stato trovato, e throwOnBindFailure
è true
.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Commenti
Questo metodo crea delegati solo per i metodi di istanza. Un metodo di istanza è un metodo associato a un'istanza di una classe; un metodo statico è un metodo associato alla classe stessa.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei metodi non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per la reflection.
Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.
Vedi anche
Si applica a
CreateDelegate(Type, MethodInfo, Boolean)
Crea un delegato del tipo indicato per rappresentare il metodo statico specificato, in cui viene indicato anche il funzionamento in caso di errore di associazione.
public:
static Delegate ^ CreateDelegate(Type ^ type, System::Reflection::MethodInfo ^ method, bool throwOnBindFailure);
public static Delegate? CreateDelegate (Type type, System.Reflection.MethodInfo method, bool throwOnBindFailure);
public static Delegate CreateDelegate (Type type, System.Reflection.MethodInfo method, bool throwOnBindFailure);
static member CreateDelegate : Type * System.Reflection.MethodInfo * bool -> Delegate
Public Shared Function CreateDelegate (type As Type, method As MethodInfo, throwOnBindFailure As Boolean) As Delegate
Parametri
- method
- MethodInfo
MethodInfo che descrive il metodo statico o il metodo di istanza che deve essere rappresentato dal delegato.
- throwOnBindFailure
- Boolean
true
per generare un'eccezione se non è possibile associare method
. In caso contrario, false
.
Restituisce
Delegato del tipo specificato che rappresenta il metodo statico specificato.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
method
non può essere associato e throwOnBindFailure
è true
.
-oppure-
method
non è un oggetto RuntimeMethodInfo
. Vedere Tipi di runtime nella reflection.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Esempio
In questa sezione sono riportati due esempi di codice. Nel primo esempio vengono illustrati i due tipi di delegati che è possibile creare con questo overload del metodo: aprire su un metodo di istanza e aprire su un metodo statico.
Il secondo esempio di codice illustra i tipi di parametro compatibili e i tipi restituiti.
Esempio 1
Nell'esempio di codice seguente vengono illustrati i due modi in cui è possibile creare un delegato usando questo overload del CreateDelegate metodo .
Nota
Esistono due overload del CreateDelegate metodo che specificano un MethodInfo argomento ma non un primo argomento. La relativa funzionalità è la stessa, ad eccezione del fatto che quella consente di specificare se generare un'eccezione in caso di errore di associazione e l'altra genera sempre . In questo esempio di codice vengono usati entrambi gli overload.
L'esempio dichiara una classe C
con un metodo M2
statico e un metodo M1
di istanza e due tipi delegati: D1
accetta un'istanza di C
e una stringa e D2
accetta una stringa.
Una seconda classe denominata Example
contiene il codice che crea i delegati.
Viene creato un delegato di tipo
D1
, che rappresenta un metodo di istanza aperto, per il metodoM1
di istanza . È necessario passare un'istanza quando viene richiamato il delegato.Viene creato un delegato di tipo
D2
, che rappresenta un metodo statico aperto, per il metodoM2
statico .
using System;
using System.Reflection;
using System.Security.Permissions;
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();
// A sample class with an instance method and a static method.
//
public class C
{
private int id;
public C(int id) { this.id = id; }
public void M1(string s)
{
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}",
this.id, s);
}
public static void M2(string s)
{
Console.WriteLine("Static method M2 on C: s = {0}", s);
}
}
public class Example
{
public static void Main()
{
C c1 = new C(42);
// Get a MethodInfo for each method.
//
MethodInfo mi1 = typeof(C).GetMethod("M1",
BindingFlags.Public | BindingFlags.Instance);
MethodInfo mi2 = typeof(C).GetMethod("M2",
BindingFlags.Public | BindingFlags.Static);
D1 d1;
D2 d2;
D3 d3;
Console.WriteLine("\nAn instance method closed over C.");
// In this case, the delegate and the
// method must have the same list of argument types; use
// delegate type D2 with instance method M1.
//
Delegate test =
Delegate.CreateDelegate(typeof(D2), c1, mi1, false);
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
//
if (test != null)
{
d2 = (D2) test;
// The same instance of C is used every time the
// delegate is invoked.
d2("Hello, World!");
d2("Hi, Mom!");
}
Console.WriteLine("\nAn open instance method.");
// In this case, the delegate has one more
// argument than the instance method; this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
//
d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);
// An instance of C must be passed in each time the
// delegate is invoked.
//
d1(c1, "Hello, World!");
d1(new C(5280), "Hi, Mom!");
Console.WriteLine("\nAn open static method.");
// In this case, the delegate and the method must
// have the same list of argument types; use delegate type
// D2 with static method M2.
//
d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);
// No instances of C are involved, because this is a static
// method.
//
d2("Hello, World!");
d2("Hi, Mom!");
Console.WriteLine("\nA static method closed over the first argument (String).");
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
//
d3 = (D3) Delegate.CreateDelegate(typeof(D3),
"Hello, World!", mi2);
// Each time the delegate is invoked, the same string is
// used.
d3();
}
}
/* This code example produces the following output:
An instance method closed over C.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 42, s = Hi, Mom!
An open instance method.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 5280, s = Hi, Mom!
An open static method.
Static method M2 on C: s = Hello, World!
Static method M2 on C: s = Hi, Mom!
A static method closed over the first argument (String).
Static method M2 on C: s = Hello, World!
*/
open System
open System.Reflection
// A sample class with an instance method and a static method.
type C(id) =
member _.M1(s) =
printfn $"Instance method M1 on C: id = %i{id}, s = %s{s}"
static member M2(s) =
printfn $"Static method M2 on C: s = %s{s}"
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit
let c1 = C 42
// Get a MethodInfo for each method.
//
let mi1 = typeof<C>.GetMethod("M1", BindingFlags.Public ||| BindingFlags.Instance)
let mi2 = typeof<C>.GetMethod("M2", BindingFlags.Public ||| BindingFlags.Static)
printfn "\nAn instance method closed over C."
// In this case, the delegate and the
// method must have the same list of argument types use
// delegate type D2 with instance method M1.
let test = Delegate.CreateDelegate(typeof<D2>, c1, mi1, false)
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
if test <> null then
let d2 = test :?> D2
// The same instance of C is used every time the
// delegate is invoked.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nAn open instance method."
// In this case, the delegate has one more
// argument than the instance method this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1
// An instance of C must be passed in each time the
// delegate is invoked.
d1.Invoke(c1, "Hello, World!")
d1.Invoke(C 5280, "Hi, Mom!")
printfn "\nAn open static method."
// In this case, the delegate and the method must
// have the same list of argument types use delegate type
// D2 with static method M2.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2
// No instances of C are involved, because this is a static
// method.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nA static method closed over the first argument (String)."
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3
// Each time the delegate is invoked, the same string is used.
d3.Invoke()
// This code example produces the following output:
// An instance method closed over C.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 42, s = Hi, Mom!
//
// An open instance method.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 5280, s = Hi, Mom!
//
// An open static method.
// Static method M2 on C: s = Hello, World!
// Static method M2 on C: s = Hi, Mom!
//
// A static method closed over the first argument (String).
// Static method M2 on C: s = Hello, World!
Imports System.Reflection
Imports System.Security.Permissions
' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String)
Public Delegate Sub D2(ByVal s As String)
Public Delegate Sub D3()
' A sample class with an instance method and a Shared method.
'
Public Class C
Private id As Integer
Public Sub New(ByVal id As Integer)
Me.id = id
End Sub
Public Sub M1(ByVal s As String)
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}", _
Me.id, s)
End Sub
Public Shared Sub M2(ByVal s As String)
Console.WriteLine("Shared method M2 on C: s = {0}", s)
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim c1 As New C(42)
' Get a MethodInfo for each method.
'
Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
BindingFlags.Public Or BindingFlags.Instance)
Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
BindingFlags.Public Or BindingFlags.Static)
Dim d1 As D1
Dim d2 As D2
Dim d3 As D3
Console.WriteLine(vbLf & "An instance method closed over C.")
' In this case, the delegate and the
' method must have the same list of argument types; use
' delegate type D2 with instance method M1.
'
Dim test As [Delegate] = _
[Delegate].CreateDelegate(GetType(D2), c1, mi1, False)
' Because False was specified for throwOnBindFailure
' in the call to CreateDelegate, the variable 'test'
' contains Nothing if the method fails to bind (for
' example, if mi1 happened to represent a method of
' some class other than C).
'
If test IsNot Nothing Then
d2 = CType(test, D2)
' The same instance of C is used every time the
' delegate is invoked.
d2("Hello, World!")
d2("Hi, Mom!")
End If
Console.WriteLine(vbLf & "An open instance method.")
' In this case, the delegate has one more
' argument than the instance method; this argument comes
' at the beginning, and represents the hidden instance
' argument of the instance method. Use delegate type D1
' with instance method M1.
'
d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
' An instance of C must be passed in each time the
' delegate is invoked.
'
d1(c1, "Hello, World!")
d1(New C(5280), "Hi, Mom!")
Console.WriteLine(vbLf & "An open Shared method.")
' In this case, the delegate and the method must
' have the same list of argument types; use delegate type
' D2 with Shared method M2.
'
d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
' No instances of C are involved, because this is a Shared
' method.
'
d2("Hello, World!")
d2("Hi, Mom!")
Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
' The delegate must omit the first argument of the method.
' A string is passed as the firstArgument parameter, and
' the delegate is bound to this string. Use delegate type
' D3 with Shared method M2.
'
d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
' Each time the delegate is invoked, the same string is
' used.
d3()
End Sub
End Class
' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C: s = Hello, World!
'Shared method M2 on C: s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C: s = Hello, World!
'
Esempio 2
Nell'esempio di codice seguente viene illustrata la compatibilità dei tipi di parametro e dei tipi restituiti.
Nota
In questo esempio di codice viene utilizzato l'overload del CreateDelegate(Type, MethodInfo) metodo . L'uso di altri overload che accettano MethodInfo è simile.
L'esempio di codice definisce una classe di base denominata Base
e una classe denominata Derived
che deriva da Base
. La classe derivata ha un static
metodo (Shared
in Visual Basic) denominato MyMethod
con un parametro di tipo Base
e un tipo restituito di Derived
. L'esempio di codice definisce anche un delegato denominato Example
con un parametro di tipo Derived
e un tipo restituito di Base
.
Nell'esempio di codice viene illustrato che il delegato denominato Example
può essere usato per rappresentare il metodo MyMethod
. Il metodo può essere associato al delegato perché:
Il tipo di parametro del delegato (
Derived
) è più restrittivo del tipo di parametro (Base
MyMethod
), in modo che sia sempre sicuro passare l'argomento del delegato aMyMethod
.Il tipo restituito di
MyMethod
(Derived
) è più restrittivo del tipo di parametro del delegato (Base
), in modo che sia sempre sicuro eseguire il cast del tipo restituito del metodo al tipo restituito del delegato.
L'esempio di codice non produce alcun output.
using namespace System;
using namespace System::Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public ref class Base {};
public ref class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public:
static Derived^ MyMethod(Base^ arg)
{
Base^ dummy = arg;
return gcnew Derived();
}
};
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);
void main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags::Public | BindingFlags::Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example^ ex =
(Example^) Delegate::CreateDelegate(Example::typeid, minfo);
// Execute MyMethod using the delegate Example.
//
Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public class Base {}
public class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public static Derived MyMethod(Base arg)
{
Base dummy = arg;
return new Derived();
}
}
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);
class Test
{
public static void Main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example ex =
(Example) Delegate.CreateDelegate(typeof(Example), minfo);
// Execute MyMethod using the delegate Example.
//
Base b = ex(new Derived());
}
}
open System
open System.Reflection
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end
type Derived() =
inherit Base()
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
static member MyMethod(arg: Base) =
Derived()
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base
// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static
// Get a MethodInfo that represents MyMethod.
let minfo = typeof<Derived>.GetMethod("MyMethod", flags)
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example
// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
Imports System.Reflection
' Define two classes to use in the demonstration, a base class and
' a class that derives from it.
'
Public Class Base
End Class
Public Class Derived
Inherits Base
' Define a Shared method to use in the demonstration. The method
' takes an instance of Base and returns an instance of Derived.
' For the purposes of the demonstration, it is not necessary for
' the method to do anything useful.
'
Public Shared Function MyMethod(ByVal arg As Base) As Derived
Dim dummy As Base = arg
Return New Derived()
End Function
End Class
' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base
Module Test
Sub Main()
' The binding flags needed to retrieve MyMethod.
Dim flags As BindingFlags = _
BindingFlags.Public Or BindingFlags.Static
' Get a MethodInfo that represents MyMethod.
Dim minfo As MethodInfo = _
GetType(Derived).GetMethod("MyMethod", flags)
' Demonstrate contravariance of parameter types and covariance
' of return types by using the delegate Example to represent
' MyMethod. The delegate binds to the method because the
' parameter of the delegate is more restrictive than the
' parameter of the method (that is, the delegate accepts an
' instance of Derived, which can always be safely passed to
' a parameter of type Base), and the return type of MyMethod
' is more restrictive than the return type of Example (that
' is, the method returns an instance of Derived, which can
' always be safely cast to type Base).
'
Dim ex As Example = CType( _
[Delegate].CreateDelegate(GetType(Example), minfo), _
Example _
)
' Execute MyMethod using the delegate Example.
'
Dim b As Base = ex(New Derived())
End Sub
End Module
Commenti
Questo overload di metodo può creare delegati del metodo statico aperti e delegati del metodo di istanza aperti, ovvero delegati che espongono il primo argomento nascosto dei metodi di istanza. Per una spiegazione dettagliata, vedere l'overload del metodo più generale CreateDelegate(Type, Object, MethodInfo, Boolean) , che consente di creare tutte le combinazioni di delegati aperti o chiusi per esempio o metodi statici.
Nota
Questo overload del metodo deve essere usato quando il delegato non viene chiuso sul primo argomento, perché è leggermente più veloce in questo caso.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessione dei metodi non pubblici è limitato al set di concessione del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per Reflection.
Per usare questa funzionalità, l'applicazione deve essere destinato a .NET Framework 3.5 o versione successiva.
Tipi di parametri compatibili e tipo restituito
I tipi di parametro e il tipo restituito di un delegato devono essere compatibili con i tipi di parametro e il tipo restituito del metodo rappresentato dal delegato; i tipi non devono corrispondere esattamente.
Un parametro di un delegato è compatibile con il parametro di un metodo corrispondente se il tipo del parametro del delegato è più restrittivo rispetto al tipo del parametro del metodo. In questo modo si garantisce che un argomento passato al delegato possa essere passato in modo sicuro al metodo.
Analogamente, il tipo restituito di un delegato è compatibile con il tipo restituito di un metodo se il tipo restituito del metodo è più restrittivo rispetto al tipo restituito del delegato. In questo modo si garantisce la possibilità di eseguire in modo sicuro il cast del valore restituito del metodo nel tipo restituito del delegato.
Ad esempio, un delegato con un parametro di tipo Hashtable e un tipo restituito di Object può rappresentare un metodo con un parametro di tipo e un valore restituito di tipo ObjectHashtable.
Vedi anche
Si applica a
CreateDelegate(Type, Object, String)
Crea un delegato del tipo specificato che rappresenta il metodo di istanza specificato per il richiamo dell'istanza di classe specificata.
public:
static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ target, System::String ^ method);
public static Delegate CreateDelegate (Type type, object target, string method);
static member CreateDelegate : Type * obj * string -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Object, method As String) As Delegate
Parametri
- target
- Object
Istanza di classe per la quale viene richiamato method
.
- method
- String
Nome del metodo di istanza che deve essere rappresentato dal delegato.
Restituisce
Delegato del tipo specificato che rappresenta il metodo di istanza specificato per il richiamo dell'istanza di classe specificata.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
method
non è un metodo di istanza.
-oppure-
Non possibile associare method
, ad esempio perché non è stato trovato.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Commenti
Questo metodo crea delegati solo per i metodi di istanza. Un metodo di istanza è un metodo associato a un'istanza di una classe; un metodo statico è un metodo associato alla classe stessa.
Questo overload di metodo equivale a chiamare l'overload del CreateDelegate(Type, Object, String, Boolean, Boolean) metodo, specificando false
per ignoreCase
e true
per throwOnBindFailure
.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessione dei metodi non pubblici è limitato al set di concessione del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per Reflection.
Per usare questa funzionalità, l'applicazione deve essere destinato a .NET Framework 3.5 o versione successiva.
Vedi anche
Si applica a
CreateDelegate(Type, Object, MethodInfo)
Crea un delegato del tipo specificato che rappresenta il metodo statico o il metodo di istanza indicato, con il primo argomento specificato.
public:
static Delegate ^ CreateDelegate(Type ^ type, System::Object ^ firstArgument, System::Reflection::MethodInfo ^ method);
public static Delegate CreateDelegate (Type type, object? firstArgument, System.Reflection.MethodInfo method);
public static Delegate CreateDelegate (Type type, object firstArgument, System.Reflection.MethodInfo method);
static member CreateDelegate : Type * obj * System.Reflection.MethodInfo -> Delegate
Public Shared Function CreateDelegate (type As Type, firstArgument As Object, method As MethodInfo) As Delegate
Parametri
- firstArgument
- Object
Oggetto a cui il delegato è associato oppure null
per trattare method
come static
(Shared
in Visual Basic).
- method
- MethodInfo
MethodInfo che descrive il metodo statico o il metodo di istanza che deve essere rappresentato dal delegato.
Restituisce
Delegato del tipo specificato che rappresenta il metodo statico o di istanza specificato.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
method
non può essere associato.
-oppure-
method
non è un oggetto RuntimeMethodInfo
. Vedere Tipi di runtime nella reflection.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Esempio
Questa sezione contiene tre esempi di codice. Il primo esempio illustra i quattro tipi di delegati che possono essere creati: chiuso su un metodo di istanza, aperto su un metodo di istanza, aperto su un metodo statico e chiuso su un metodo statico.
Il secondo esempio di codice illustra i tipi di parametri compatibili e i tipi restituiti.
Il terzo esempio di codice definisce un singolo tipo delegato e mostra tutti i metodi che il tipo delegato può rappresentare.
Esempio 1
Nell'esempio di codice seguente vengono illustrati i quattro modi in cui è possibile creare un delegato usando questo overload del CreateDelegate metodo.
Nota
Esistono due overload del metodo che specificano firstArgument
e un MethodInfo. La loro funzionalità è la stessa, ad eccezione del CreateDelegate fatto che quella consente di specificare se generare un errore di associazione e l'altra genera sempre. Questo esempio di codice usa entrambi gli overload.
L'esempio dichiara una classe C
con un metodo statico e un metodo M1
M2
di istanza e tre tipi di delegato: D1
accetta un'istanza di C
e una stringa, D2
accetta una stringa e D3
non ha argomenti.
Una seconda classe denominata Example
contiene il codice che crea i delegati.
Viene creato un delegato di tipo
D2
, chiuso su un'istanza diC
, per il metodoM1
di istanza . Viene richiamato con stringhe diverse, per mostrare che l'istanza associata diC
viene sempre usata.Viene creato un delegato di tipo
D1
, che rappresenta un metodo di istanza aperto, per il metodoM1
di istanza . Quando viene richiamato il delegato, è necessario passare un'istanza.Viene creato un delegato di tipo
D2
, che rappresenta un metodo statico aperto, per il metodoM2
statico .Infine, un delegato di tipo
D3
, chiuso su una stringa, viene creato per il metodoM2
statico . Il metodo viene richiamato per mostrare che usa la stringa associata.
using System;
using System.Reflection;
using System.Security.Permissions;
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();
// A sample class with an instance method and a static method.
//
public class C
{
private int id;
public C(int id) { this.id = id; }
public void M1(string s)
{
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}",
this.id, s);
}
public static void M2(string s)
{
Console.WriteLine("Static method M2 on C: s = {0}", s);
}
}
public class Example
{
public static void Main()
{
C c1 = new C(42);
// Get a MethodInfo for each method.
//
MethodInfo mi1 = typeof(C).GetMethod("M1",
BindingFlags.Public | BindingFlags.Instance);
MethodInfo mi2 = typeof(C).GetMethod("M2",
BindingFlags.Public | BindingFlags.Static);
D1 d1;
D2 d2;
D3 d3;
Console.WriteLine("\nAn instance method closed over C.");
// In this case, the delegate and the
// method must have the same list of argument types; use
// delegate type D2 with instance method M1.
//
Delegate test =
Delegate.CreateDelegate(typeof(D2), c1, mi1, false);
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
//
if (test != null)
{
d2 = (D2) test;
// The same instance of C is used every time the
// delegate is invoked.
d2("Hello, World!");
d2("Hi, Mom!");
}
Console.WriteLine("\nAn open instance method.");
// In this case, the delegate has one more
// argument than the instance method; this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
//
d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);
// An instance of C must be passed in each time the
// delegate is invoked.
//
d1(c1, "Hello, World!");
d1(new C(5280), "Hi, Mom!");
Console.WriteLine("\nAn open static method.");
// In this case, the delegate and the method must
// have the same list of argument types; use delegate type
// D2 with static method M2.
//
d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);
// No instances of C are involved, because this is a static
// method.
//
d2("Hello, World!");
d2("Hi, Mom!");
Console.WriteLine("\nA static method closed over the first argument (String).");
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
//
d3 = (D3) Delegate.CreateDelegate(typeof(D3),
"Hello, World!", mi2);
// Each time the delegate is invoked, the same string is
// used.
d3();
}
}
/* This code example produces the following output:
An instance method closed over C.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 42, s = Hi, Mom!
An open instance method.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 5280, s = Hi, Mom!
An open static method.
Static method M2 on C: s = Hello, World!
Static method M2 on C: s = Hi, Mom!
A static method closed over the first argument (String).
Static method M2 on C: s = Hello, World!
*/
open System
open System.Reflection
// A sample class with an instance method and a static method.
type C(id) =
member _.M1(s) =
printfn $"Instance method M1 on C: id = %i{id}, s = %s{s}"
static member M2(s) =
printfn $"Static method M2 on C: s = %s{s}"
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit
let c1 = C 42
// Get a MethodInfo for each method.
//
let mi1 = typeof<C>.GetMethod("M1", BindingFlags.Public ||| BindingFlags.Instance)
let mi2 = typeof<C>.GetMethod("M2", BindingFlags.Public ||| BindingFlags.Static)
printfn "\nAn instance method closed over C."
// In this case, the delegate and the
// method must have the same list of argument types use
// delegate type D2 with instance method M1.
let test = Delegate.CreateDelegate(typeof<D2>, c1, mi1, false)
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
if test <> null then
let d2 = test :?> D2
// The same instance of C is used every time the
// delegate is invoked.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nAn open instance method."
// In this case, the delegate has one more
// argument than the instance method this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1
// An instance of C must be passed in each time the
// delegate is invoked.
d1.Invoke(c1, "Hello, World!")
d1.Invoke(C 5280, "Hi, Mom!")
printfn "\nAn open static method."
// In this case, the delegate and the method must
// have the same list of argument types use delegate type
// D2 with static method M2.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2
// No instances of C are involved, because this is a static
// method.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nA static method closed over the first argument (String)."
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3
// Each time the delegate is invoked, the same string is used.
d3.Invoke()
// This code example produces the following output:
// An instance method closed over C.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 42, s = Hi, Mom!
//
// An open instance method.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 5280, s = Hi, Mom!
//
// An open static method.
// Static method M2 on C: s = Hello, World!
// Static method M2 on C: s = Hi, Mom!
//
// A static method closed over the first argument (String).
// Static method M2 on C: s = Hello, World!
Imports System.Reflection
Imports System.Security.Permissions
' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String)
Public Delegate Sub D2(ByVal s As String)
Public Delegate Sub D3()
' A sample class with an instance method and a Shared method.
'
Public Class C
Private id As Integer
Public Sub New(ByVal id As Integer)
Me.id = id
End Sub
Public Sub M1(ByVal s As String)
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}", _
Me.id, s)
End Sub
Public Shared Sub M2(ByVal s As String)
Console.WriteLine("Shared method M2 on C: s = {0}", s)
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim c1 As New C(42)
' Get a MethodInfo for each method.
'
Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
BindingFlags.Public Or BindingFlags.Instance)
Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
BindingFlags.Public Or BindingFlags.Static)
Dim d1 As D1
Dim d2 As D2
Dim d3 As D3
Console.WriteLine(vbLf & "An instance method closed over C.")
' In this case, the delegate and the
' method must have the same list of argument types; use
' delegate type D2 with instance method M1.
'
Dim test As [Delegate] = _
[Delegate].CreateDelegate(GetType(D2), c1, mi1, False)
' Because False was specified for throwOnBindFailure
' in the call to CreateDelegate, the variable 'test'
' contains Nothing if the method fails to bind (for
' example, if mi1 happened to represent a method of
' some class other than C).
'
If test IsNot Nothing Then
d2 = CType(test, D2)
' The same instance of C is used every time the
' delegate is invoked.
d2("Hello, World!")
d2("Hi, Mom!")
End If
Console.WriteLine(vbLf & "An open instance method.")
' In this case, the delegate has one more
' argument than the instance method; this argument comes
' at the beginning, and represents the hidden instance
' argument of the instance method. Use delegate type D1
' with instance method M1.
'
d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
' An instance of C must be passed in each time the
' delegate is invoked.
'
d1(c1, "Hello, World!")
d1(New C(5280), "Hi, Mom!")
Console.WriteLine(vbLf & "An open Shared method.")
' In this case, the delegate and the method must
' have the same list of argument types; use delegate type
' D2 with Shared method M2.
'
d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
' No instances of C are involved, because this is a Shared
' method.
'
d2("Hello, World!")
d2("Hi, Mom!")
Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
' The delegate must omit the first argument of the method.
' A string is passed as the firstArgument parameter, and
' the delegate is bound to this string. Use delegate type
' D3 with Shared method M2.
'
d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
' Each time the delegate is invoked, the same string is
' used.
d3()
End Sub
End Class
' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C: s = Hello, World!
'Shared method M2 on C: s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C: s = Hello, World!
'
Esempio 2
Nell'esempio di codice seguente viene illustrata la compatibilità dei tipi di parametri e dei tipi restituiti.
Nota
Questo esempio di codice usa l'overload del CreateDelegate(Type, MethodInfo) metodo. L'uso di altri overload che accettano MethodInfo è simile.
L'esempio di codice definisce una classe di base denominata Base
e una classe denominata Derived
che deriva da Base
. La classe derivata ha un static
metodo (Shared
in Visual Basic) denominato MyMethod
con un parametro di tipo Base
e un tipo restituito di Derived
. L'esempio di codice definisce anche un delegato denominato Example
con un parametro di tipo Derived
e un tipo restituito di Base
.
Nell'esempio di codice viene illustrato che il delegato denominato Example
può essere usato per rappresentare il metodo MyMethod
. Il metodo può essere associato al delegato perché:
Il tipo di parametro del delegato () è più restrittivo del tipo
MyMethod
di parametro (Base
Derived
), in modo che sia sempre sicuro passare l'argomento del delegato aMyMethod
.Il tipo restituito di
MyMethod
(Derived
) è più restrittivo del tipo di parametro del delegato (Base
), in modo che sia sempre sicuro eseguire il cast del tipo restituito del metodo al tipo restituito del delegato.
L'esempio di codice non produce alcun output.
using namespace System;
using namespace System::Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public ref class Base {};
public ref class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public:
static Derived^ MyMethod(Base^ arg)
{
Base^ dummy = arg;
return gcnew Derived();
}
};
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);
void main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags::Public | BindingFlags::Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example^ ex =
(Example^) Delegate::CreateDelegate(Example::typeid, minfo);
// Execute MyMethod using the delegate Example.
//
Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public class Base {}
public class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public static Derived MyMethod(Base arg)
{
Base dummy = arg;
return new Derived();
}
}
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);
class Test
{
public static void Main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example ex =
(Example) Delegate.CreateDelegate(typeof(Example), minfo);
// Execute MyMethod using the delegate Example.
//
Base b = ex(new Derived());
}
}
open System
open System.Reflection
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end
type Derived() =
inherit Base()
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
static member MyMethod(arg: Base) =
Derived()
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base
// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static
// Get a MethodInfo that represents MyMethod.
let minfo = typeof<Derived>.GetMethod("MyMethod", flags)
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example
// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
Imports System.Reflection
' Define two classes to use in the demonstration, a base class and
' a class that derives from it.
'
Public Class Base
End Class
Public Class Derived
Inherits Base
' Define a Shared method to use in the demonstration. The method
' takes an instance of Base and returns an instance of Derived.
' For the purposes of the demonstration, it is not necessary for
' the method to do anything useful.
'
Public Shared Function MyMethod(ByVal arg As Base) As Derived
Dim dummy As Base = arg
Return New Derived()
End Function
End Class
' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base
Module Test
Sub Main()
' The binding flags needed to retrieve MyMethod.
Dim flags As BindingFlags = _
BindingFlags.Public Or BindingFlags.Static
' Get a MethodInfo that represents MyMethod.
Dim minfo As MethodInfo = _
GetType(Derived).GetMethod("MyMethod", flags)
' Demonstrate contravariance of parameter types and covariance
' of return types by using the delegate Example to represent
' MyMethod. The delegate binds to the method because the
' parameter of the delegate is more restrictive than the
' parameter of the method (that is, the delegate accepts an
' instance of Derived, which can always be safely passed to
' a parameter of type Base), and the return type of MyMethod
' is more restrictive than the return type of Example (that
' is, the method returns an instance of Derived, which can
' always be safely cast to type Base).
'
Dim ex As Example = CType( _
[Delegate].CreateDelegate(GetType(Example), minfo), _
Example _
)
' Execute MyMethod using the delegate Example.
'
Dim b As Base = ex(New Derived())
End Sub
End Module
Esempio 3
Nell'esempio di codice seguente vengono illustrati tutti i metodi che possono rappresentare un singolo tipo di delegato usando il CreateDelegate metodo per creare i delegati.
Nota
Esistono due overload del metodo che specificano firstArgument
e un MethodInfo. La loro funzionalità è la stessa, ad eccezione del CreateDelegate fatto che quella consente di specificare se generare un errore di associazione e l'altra genera sempre. Questo esempio di codice usa entrambi gli overload.
L'esempio di codice definisce due classi C
e F
e un tipo D
delegato con un argomento di tipo C
. Le classi hanno metodi M1
statici e di istanza corrispondenti, M3
e M4
C
hanno anche un metodo M2
di istanza senza argomenti.
Una terza classe denominata Example
contiene il codice che crea i delegati.
I delegati vengono creati per il metodo
M1
di istanza di tipoC
e tipoF
. Ogni viene chiuso su un'istanza del rispettivo tipo. Il metodoM1
di tipoC
visualizza leID
proprietà dell'istanza associata e dell'argomento.Viene creato un delegato per il metodo
M2
di tipoC
. Si tratta di un delegato di istanza aperta, in cui l'argomento del delegato rappresenta il primo argomento nascosto nel metodo dell'istanza. Il metodo non ha altri argomenti. Viene chiamato come se fosse un metodo statico.I delegati vengono creati per il metodo
M3
statico di tipoC
e tipoF
. Questi sono delegati statici aperti.Infine, i delegati vengono creati per il metodo statico di tipo
C
eF
tipo. Ogni metodoM4
ha il tipo dichiarante come primo argomento e viene fornita un'istanza del tipo, pertanto i delegati vengono chiusi sui primi argomenti. Il metodoM4
di tipoC
visualizza leID
proprietà dell'istanza associata e dell'argomento.
using System;
using System.Reflection;
using System.Security.Permissions;
// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
//
public delegate void D(C c);
// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
//
public class C
{
private int id;
public int ID { get { return id; }}
public C(int id) { this.id = id; }
public void M1(C c)
{
Console.WriteLine("Instance method M1(C c) on C: this.id = {0}, c.ID = {1}",
this.id, c.ID);
}
public void M2()
{
Console.WriteLine("Instance method M2() on C: this.id = {0}",
this.id);
}
public static void M3(C c)
{
Console.WriteLine("Static method M3(C c) on C: c.ID = {0}", c.ID);
}
public static void M4(C c1, C c2)
{
Console.WriteLine("Static method M4(C c1, C c2) on C: c1.ID = {0}, c2.ID = {1}",
c1.ID, c2.ID);
}
}
public class F
{
public void M1(C c)
{
Console.WriteLine("Instance method M1(C c) on F: c.ID = {0}",
c.ID);
}
public static void M3(C c)
{
Console.WriteLine("Static method M3(C c) on F: c.ID = {0}", c.ID);
}
public static void M4(F f, C c)
{
Console.WriteLine("Static method M4(F f, C c) on F: c.ID = {0}",
c.ID);
}
}
public class Example
{
public static void Main()
{
C c1 = new C(42);
C c2 = new C(1491);
F f1 = new F();
D d;
// Instance method with one argument of type C.
MethodInfo cmi1 = typeof(C).GetMethod("M1");
// Instance method with no arguments.
MethodInfo cmi2 = typeof(C).GetMethod("M2");
// Static method with one argument of type C.
MethodInfo cmi3 = typeof(C).GetMethod("M3");
// Static method with two arguments of type C.
MethodInfo cmi4 = typeof(C).GetMethod("M4");
// Instance method with one argument of type C.
MethodInfo fmi1 = typeof(F).GetMethod("M1");
// Static method with one argument of type C.
MethodInfo fmi3 = typeof(F).GetMethod("M3");
// Static method with an argument of type F and an argument
// of type C.
MethodInfo fmi4 = typeof(F).GetMethod("M4");
Console.WriteLine("\nAn instance method on any type, with an argument of type C.");
// D can represent any instance method that exactly matches its
// signature. Methods on C and F are shown here.
//
d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi1);
d(c2);
d = (D) Delegate.CreateDelegate(typeof(D), f1, fmi1);
d(c2);
Console.WriteLine("\nAn instance method on C with no arguments.");
// D can represent an instance method on C that has no arguments;
// in this case, the argument of D represents the hidden first
// argument of any instance method. The delegate acts like a
// static method, and an instance of C must be passed each time
// it is invoked.
//
d = (D) Delegate.CreateDelegate(typeof(D), null, cmi2);
d(c1);
Console.WriteLine("\nA static method on any type, with an argument of type C.");
// D can represent any static method with the same signature.
// Methods on F and C are shown here.
//
d = (D) Delegate.CreateDelegate(typeof(D), null, cmi3);
d(c1);
d = (D) Delegate.CreateDelegate(typeof(D), null, fmi3);
d(c1);
Console.WriteLine("\nA static method on any type, with an argument of");
Console.WriteLine(" that type and an argument of type C.");
// D can represent any static method with one argument of the
// type the method belongs and a second argument of type C.
// In this case, the method is closed over the instance of
// supplied for the its first argument, and acts like an instance
// method. Methods on F and C are shown here.
//
d = (D) Delegate.CreateDelegate(typeof(D), c1, cmi4);
d(c2);
Delegate test =
Delegate.CreateDelegate(typeof(D), f1, fmi4, false);
// This final example specifies false for throwOnBindFailure
// in the call to CreateDelegate, so the variable 'test'
// contains Nothing if the method fails to bind (for
// example, if fmi4 happened to represent a method of
// some class other than F).
//
if (test != null)
{
d = (D) test;
d(c2);
}
}
}
/* This code example produces the following output:
An instance method on any type, with an argument of type C.
Instance method M1(C c) on C: this.id = 42, c.ID = 1491
Instance method M1(C c) on F: c.ID = 1491
An instance method on C with no arguments.
Instance method M2() on C: this.id = 42
A static method on any type, with an argument of type C.
Static method M3(C c) on C: c.ID = 42
Static method M3(C c) on F: c.ID = 42
A static method on any type, with an argument of
that type and an argument of type C.
Static method M4(C c1, C c2) on C: c1.ID = 42, c2.ID = 1491
Static method M4(F f, C c) on F: c.ID = 1491
*/
open System
// Declare two sample classes, C and F. Class C has an ID
// property so instances can be identified.
type C(id) =
member _.ID = id
member _.M1(c: C) =
printfn $"Instance method M1(C c) on C: this.id = {id}, c.ID = {c.ID}"
member _.M2() =
printfn $"Instance method M2() on C: this.id = {id}"
static member M3(c: C) =
printfn $"Static method M3(C c) on C: c.ID = {c.ID}"
static member M4(c1: C, c2: C) =
printfn $"Static method M4(C c1, C c2) on C: c1.ID = {c1.ID}, c2.ID = {c2.ID}"
// Declare a delegate type. The object of this code example
// is to show all the methods this delegate can bind to.
type D = delegate of C -> unit
type F() =
member _.M1(c: C) =
printfn $"Instance method M1(C c) on F: c.ID = {c.ID}"
member _.M3(c: C) =
printfn $"Static method M3(C c) on F: c.ID = {c.ID}"
member _.M4(f: F, c: C) =
printfn $"Static method M4(F f, C c) on F: c.ID = {c.ID}"
[<EntryPoint>]
let main _ =
let c1 = C 42
let c2 = C 1491
let f1 = F()
// Instance method with one argument of type C.
let cmi1 = typeof<C>.GetMethod "M1"
// Instance method with no arguments.
let cmi2 = typeof<C>.GetMethod "M2"
// Static method with one argument of type C.
let cmi3 = typeof<C>.GetMethod "M3"
// Static method with two arguments of type C.
let cmi4 = typeof<C>.GetMethod "M4"
// Instance method with one argument of type C.
let fmi1 = typeof<F>.GetMethod "M1"
// Static method with one argument of type C.
let fmi3 = typeof<F>.GetMethod "M3"
// Static method with an argument of type F and an argument
// of type C.
let fmi4 = typeof<F>.GetMethod "M4"
printfn "\nAn instance method on any type, with an argument of type C."
// D can represent any instance method that exactly matches its
// signature. Methods on C and F are shown here.
let d = Delegate.CreateDelegate(typeof<D>, c1, cmi1) :?> D
d.Invoke c2
let d = Delegate.CreateDelegate(typeof<D>, f1, fmi1) :?> D
d.Invoke c2
Console.WriteLine("\nAn instance method on C with no arguments.")
// D can represent an instance method on C that has no arguments
// in this case, the argument of D represents the hidden first
// argument of any instance method. The delegate acts like a
// static method, and an instance of C must be passed each time
// it is invoked.
let d = Delegate.CreateDelegate(typeof<D>, null, cmi2) :?> D
d.Invoke c1
printfn "\nA static method on any type, with an argument of type C."
// D can represent any static method with the same signature.
// Methods on F and C are shown here.
let d = Delegate.CreateDelegate(typeof<D>, null, cmi3) :?> D
d.Invoke c1
let d = Delegate.CreateDelegate(typeof<D>, null, fmi3) :?> D
d.Invoke c1
printfn "\nA static method on any type, with an argument of"
printfn " that type and an argument of type C."
// D can represent any static method with one argument of the
// type the method belongs and a second argument of type C.
// In this case, the method is closed over the instance of
// supplied for the its first argument, and acts like an instance
// method. Methods on F and C are shown here.
let d = Delegate.CreateDelegate(typeof<D>, c1, cmi4) :?> D
d.Invoke c2
let test =
Delegate.CreateDelegate(typeof<D>, f1, fmi4, false)
// This final example specifies false for throwOnBindFailure
// in the call to CreateDelegate, so the variable 'test'
// contains Nothing if the method fails to bind (for
// example, if fmi4 happened to represent a method of
// some class other than F).
match test with
| :? D as d ->
d.Invoke c2
| _ -> ()
0
// This code example produces the following output:
// An instance method on any type, with an argument of type C.
// Instance method M1(C c) on C: this.id = 42, c.ID = 1491
// Instance method M1(C c) on F: c.ID = 1491
//
// An instance method on C with no arguments.
// Instance method M2() on C: this.id = 42
//
// A static method on any type, with an argument of type C.
// Static method M3(C c) on C: c.ID = 42
// Static method M3(C c) on F: c.ID = 42
//
// A static method on any type, with an argument of
// that type and an argument of type C.
// Static method M4(C c1, C c2) on C: c1.ID = 42, c2.ID = 1491
// Static method M4(F f, C c) on F: c.ID = 1491
Imports System.Reflection
Imports System.Security.Permissions
' Declare a delegate type. The object of this code example
' is to show all the methods this delegate can bind to.
'
Public Delegate Sub D(ByVal c As C)
' Declare two sample classes, C and F. Class C has an ID
' property so instances can be identified.
'
Public Class C
Private _id As Integer
Public ReadOnly Property ID() As Integer
Get
Return _id
End Get
End Property
Public Sub New(ByVal newId As Integer)
Me._id = newId
End Sub
Public Sub M1(ByVal c As C)
Console.WriteLine("Instance method M1(c As C) on C: this.id = {0}, c.ID = {1}", _
Me.id, c.ID)
End Sub
Public Sub M2()
Console.WriteLine("Instance method M2() on C: this.id = {0}", Me.id)
End Sub
Public Shared Sub M3(ByVal c As C)
Console.WriteLine("Shared method M3(c As C) on C: c.ID = {0}", c.ID)
End Sub
Public Shared Sub M4(ByVal c1 As C, ByVal c2 As C)
Console.WriteLine("Shared method M4(c1 As C, c2 As C) on C: c1.ID = {0}, c2.ID = {1}", _
c1.ID, c2.ID)
End Sub
End Class
Public Class F
Public Sub M1(ByVal c As C)
Console.WriteLine("Instance method M1(c As C) on F: c.ID = {0}", c.ID)
End Sub
Public Shared Sub M3(ByVal c As C)
Console.WriteLine("Shared method M3(c As C) on F: c.ID = {0}", c.ID)
End Sub
Public Shared Sub M4(ByVal f As F, ByVal c As C)
Console.WriteLine("Shared method M4(f As F, c As C) on F: c.ID = {0}", c.ID)
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim c1 As New C(42)
Dim c2 As New C(1491)
Dim f1 As New F()
Dim d As D
' Instance method with one argument of type C.
Dim cmi1 As MethodInfo = GetType(C).GetMethod("M1")
' Instance method with no arguments.
Dim cmi2 As MethodInfo = GetType(C).GetMethod("M2")
' Shared method with one argument of type C.
Dim cmi3 As MethodInfo = GetType(C).GetMethod("M3")
' Shared method with two arguments of type C.
Dim cmi4 As MethodInfo = GetType(C).GetMethod("M4")
' Instance method with one argument of type C.
Dim fmi1 As MethodInfo = GetType(F).GetMethod("M1")
' Shared method with one argument of type C.
Dim fmi3 As MethodInfo = GetType(F).GetMethod("M3")
' Shared method with an argument of type F and an
' argument of type C.
Dim fmi4 As MethodInfo = GetType(F).GetMethod("M4")
Console.WriteLine(vbLf & "An instance method on any type, with an argument of type C.")
' D can represent any instance method that exactly matches its
' signature. Methods on C and F are shown here.
'
d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi1), D)
d(c2)
d = CType([Delegate].CreateDelegate(GetType(D), f1, fmi1), D)
d(c2)
Console.WriteLine(vbLf & "An instance method on C with no arguments.")
' D can represent an instance method on C that has no arguments;
' in this case, the argument of D represents the hidden first
' argument of any instance method. The delegate acts like a
' Shared method, and an instance of C must be passed each time
' it is invoked.
'
d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi2), D)
d(c1)
Console.WriteLine(vbLf & "A Shared method on any type, with an argument of type C.")
' D can represent any Shared method with the same signature.
' Methods on F and C are shown here.
'
d = CType([Delegate].CreateDelegate(GetType(D), Nothing, cmi3), D)
d(c1)
d = CType([Delegate].CreateDelegate(GetType(D), Nothing, fmi3), D)
d(c1)
Console.WriteLine(vbLf & "A Shared method on any type, with an argument of")
Console.WriteLine(" that type and an argument of type C.")
' D can represent any Shared method with one argument of the
' type the method belongs and a second argument of type C.
' In this case, the method is closed over the instance of
' supplied for the its first argument, and acts like an instance
' method. Methods on F and C are shown here.
'
d = CType([Delegate].CreateDelegate(GetType(D), c1, cmi4), D)
d(c2)
Dim test As [Delegate] = _
[Delegate].CreateDelegate(GetType(D), f1, fmi4, false)
' This final example specifies False for throwOnBindFailure
' in the call to CreateDelegate, so the variable 'test'
' contains Nothing if the method fails to bind (for
' example, if fmi4 happened to represent a method of
' some class other than F).
'
If test IsNot Nothing Then
d = CType(test, D)
d(c2)
End If
End Sub
End Class
' This code example produces the following output:
'
'An instance method on any type, with an argument of type C.
'Instance method M1(c As C) on C: this.id = 42, c.ID = 1491
'Instance method M1(c As C) on F: c.ID = 1491
'
'An instance method on C with no arguments.
'Instance method M2() on C: this.id = 42
'
'A Shared method on any type, with an argument of type C.
'Shared method M3(c As C) on C: c.ID = 42
'Shared method M3(c As C) on F: c.ID = 42
'
'A Shared method on any type, with an argument of
' that type and an argument of type C.
'Shared method M4(c1 As C, c2 As C) on C: c1.ID = 42, c2.ID = 1491
'Shared method M4(f As F, c As C) on F: c.ID = 1491
'
Commenti
La chiamata di questo overload di metodo equivale a chiamare l'overload del CreateDelegate(Type, Object, MethodInfo, Boolean) metodo e specificare true
per throwOnBindFailure
. Questi due overload offrono il modo più flessibile per creare delegati. È possibile usarli per creare delegati per i metodi statici o di istanza e facoltativamente per specificare il primo argomento.
Nota
Se non si specifica un primo argomento, usare l'overload del CreateDelegate(Type, MethodInfo) metodo per migliorare le prestazioni.
Il tipo delegato e il metodo devono avere tipi restituiti compatibili. Ovvero, il tipo restituito di method
deve essere assegnabile al tipo restituito di type
.
Se firstArgument
viene specificato, viene passato a method
ogni volta che viene richiamato il delegato. firstArgument
Viene detto che deve essere associato al delegato e il delegato viene detto chiuso sul primo argomento. Se method
è (Shared
in Visual Basic), l'elenco di argomenti fornito quando richiama il delegato include tutti i parametri tranne il primo; se method
è static
un metodo di istanza, viene firstArgument
passato al parametro dell'istanza nascosta (rappresentato da this
in C#o da Me
in Visual Basic).
Se firstArgument
viene specificato, il primo parametro di deve essere un tipo di method
riferimento e firstArgument
deve essere compatibile con tale tipo.
Importante
Se method
è static
(Shared
in Visual Basic) e il primo parametro è di tipo Object o ValueType, può firstArgument
essere un tipo di valore. In questo caso firstArgument
viene automaticamente casellata. La casella automatica non si verifica per altri argomenti, perché in una chiamata di funzione C# o Visual Basic.
Se firstArgument
è un riferimento Null ed method
è un metodo di istanza, il risultato dipende dalle firme del tipo type
delegato e da method
:
Se la firma di
type
include in modo esplicito il primo parametro nascosto di , il delegato viene detto di rappresentare un metodo dimethod
istanza aperta. Quando viene richiamato il delegato, il primo argomento nell'elenco di argomenti viene passato al parametro di istanza nascosto dimethod
.Se le firme di e
type
corrispondono ,ovvero tutti i tipi dimethod
parametri sono compatibili, il delegato viene detto chiuso su un riferimento Null. Richiamare il delegato è come chiamare un metodo di istanza in un'istanza Null, che non è una cosa particolarmente utile da eseguire.
Se firstArgument
è un riferimento Null ed method
è statico, il risultato dipende dalle firme del tipo type
delegato e di method
:
Se la firma di e
type
corrispondenze ,ovvero tutti i tipi dimethod
parametro sono compatibili, il delegato viene detto di rappresentare un metodo statico aperto. Si tratta del caso più comune per i metodi statici. In questo caso, è possibile ottenere prestazioni leggermente migliori usando l'overload del CreateDelegate(Type, MethodInfo) metodo.Se la firma di
type
inizia con il secondo parametro dimethod
e il resto dei tipi di parametro sono compatibili, il delegato viene detto di essere chiuso su un riferimento Null. Quando viene richiamato il delegato, viene passato un riferimento Null al primo parametro dimethod
.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessione dei metodi non pubblici è limitato al set di concessione del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per Reflection.
Per usare questa funzionalità, l'applicazione deve essere destinato a .NET Framework 3.5 o versione successiva.
Tipi di parametri compatibili e tipo restituito
I tipi di parametro e il tipo restituito di un delegato devono essere compatibili con i tipi di parametro e il tipo restituito del metodo rappresentato dal delegato; i tipi non devono corrispondere esattamente.
Un parametro di un delegato è compatibile con il parametro di un metodo corrispondente se il tipo del parametro del delegato è più restrittivo rispetto al tipo del parametro del metodo. In questo modo si garantisce che un argomento passato al delegato possa essere passato in modo sicuro al metodo.
Analogamente, il tipo restituito di un delegato è compatibile con il tipo restituito di un metodo se il tipo restituito del metodo è più restrittivo rispetto al tipo restituito del delegato. In questo modo si garantisce la possibilità di eseguire in modo sicuro il cast del valore restituito del metodo nel tipo restituito del delegato.
Ad esempio, un delegato con un parametro di tipo Hashtable e un tipo restituito di Object può rappresentare un metodo con un parametro di tipo e un valore restituito di tipo ObjectHashtable.
Determinazione dei metodi che un delegato può rappresentare
Un altro modo utile per pensare alla flessibilità fornita da questo overload è che qualsiasi delegato specificato può rappresentare quattro combinazioni diverse di firma del metodo e tipo di CreateDelegate metodo (statico rispetto all'istanza). Prendere in considerazione un tipo D
delegato con un argomento di tipo C
. Di seguito vengono descritti i metodi D
che possono rappresentare, ignorando il tipo restituito perché deve corrispondere in tutti i casi:
D
può rappresentare qualsiasi metodo di istanza con esattamente un argomento di tipoC
, indipendentemente dal tipo a cui appartiene il metodo dell'istanza. Quando CreateDelegate viene chiamato,firstArgument
è un'istanza del tipomethod
a cui appartiene e il delegato risultante viene detto chiuso su tale istanza. (In modo semplice,D
può anche essere chiuso su un riferimento Null sefirstArgument
è un riferimento Null.D
può rappresentare un metodo di istanza di cheC
non ha argomenti. Quando CreateDelegate viene chiamato,firstArgument
è un riferimento Null. Il delegato risultante rappresenta un metodo di istanza aperta e un'istanza diC
deve essere fornita ogni volta che viene richiamata.D
può rappresentare un metodo statico che accetta un argomento di tipoC
e tale metodo può appartenere a qualsiasi tipo. Quando CreateDelegate viene chiamato,firstArgument
è un riferimento Null. Il delegato risultante rappresenta un metodo statico aperto e un'istanza diC
deve essere fornita ogni volta che viene richiamata.D
può rappresentare un metodo statico che appartiene al tipoF
e include due argomenti, di tipoF
e tipoC
. Quando CreateDelegate viene chiamato,firstArgument
è un'istanza diF
. Il delegato risultante rappresenta un metodo statico chiuso su tale istanza diF
. Si noti che nel caso in cuiF
eC
siano lo stesso tipo, il metodo statico ha due argomenti di tale tipo. In questo caso,D
viene chiuso su un riferimento Null sefirstArgument
è un riferimento Null.
Vedi anche
Si applica a
CreateDelegate(Type, Type, String)
Crea un delegato del tipo specificato che rappresenta il metodo statico specificato della classe specificata.
public:
static Delegate ^ CreateDelegate(Type ^ type, Type ^ target, System::String ^ method);
public static Delegate CreateDelegate (Type type, Type target, string method);
static member CreateDelegate : Type * Type * string -> Delegate
Public Shared Function CreateDelegate (type As Type, target As Type, method As String) As Delegate
Parametri
- method
- String
Nome del metodo statico che deve essere rappresentato dal delegato.
Restituisce
Delegato del tipo specificato che rappresenta il metodo statico specificato della classe specificata.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
target
non è un oggetto RuntimeType
.
-oppure-
target
è un tipo generico aperto. Ciò significa che la proprietà ContainsGenericParameters è true
.
-oppure-
method
non è un metodo static
(metodo Shared
in Visual Basic).
-oppure-
Non è possibile associare method
, ad esempio perché non è stato trovato, e throwOnBindFailure
è true
.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Commenti
Questo metodo crea delegati solo per i metodi statici. Un metodo di istanza è un metodo associato a un'istanza di una classe; un metodo statico è un metodo associato alla classe stessa.
Questo overload di metodo equivale a chiamare l'overload del CreateDelegate(Type, Type, String, Boolean, Boolean) metodo, specificando false
per ignoreCase
e true
per throwOnBindFailure
.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessione dei metodi non pubblici è limitato al set di concessione del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per Reflection.
Per usare questa funzionalità, l'applicazione deve essere destinato a .NET Framework 3.5 o versione successiva.
Vedi anche
Si applica a
CreateDelegate(Type, MethodInfo)
Crea un delegato del tipo specificato per rappresentare il metodo specificato.
public:
static Delegate ^ CreateDelegate(Type ^ type, System::Reflection::MethodInfo ^ method);
public static Delegate CreateDelegate (Type type, System.Reflection.MethodInfo method);
static member CreateDelegate : Type * System.Reflection.MethodInfo -> Delegate
Public Shared Function CreateDelegate (type As Type, method As MethodInfo) As Delegate
Parametri
- method
- MethodInfo
MethodInfo che descrive il metodo statico o il metodo di istanza che deve essere rappresentato dal delegato.
Restituisce
Delegato del tipo specificato per rappresentare il metodo specificato.
Eccezioni
type
non eredita MulticastDelegate.
-oppure-
type
non è un oggetto RuntimeType
. Vedere Tipi di runtime nella reflection.
-oppure-
method
non può essere associato.
-oppure-
method
non è un oggetto RuntimeMethodInfo
. Vedere Tipi di runtime nella reflection.
Non è possibile trovare il metodo Invoke
di type
.
Il chiamante non ha le autorizzazioni necessarie per accedere a method
.
Esempio
In questa sezione sono riportati due esempi di codice. Nel primo esempio vengono illustrati i due tipi di delegati che è possibile creare con questo overload del metodo: aprire su un metodo di istanza e aprire su un metodo statico.
Il secondo esempio di codice illustra i tipi di parametro compatibili e i tipi restituiti.
Esempio 1
Nell'esempio di codice seguente vengono illustrati i due modi in cui è possibile creare un delegato usando questo overload del CreateDelegate metodo .
Nota
Esistono due overload del CreateDelegate metodo che specificano un MethodInfo argomento ma non un primo argomento. La relativa funzionalità è la stessa, ad eccezione del fatto che quella consente di specificare se generare un'eccezione in caso di errore di associazione e l'altra genera sempre . In questo esempio di codice vengono usati entrambi gli overload.
L'esempio dichiara una classe C
con un metodo M2
statico e un metodo M1
di istanza e due tipi delegati: D1
accetta un'istanza di C
e una stringa e D2
accetta una stringa.
Una seconda classe denominata Example
contiene il codice che crea i delegati.
Viene creato un delegato di tipo
D1
, che rappresenta un metodo di istanza aperto, per il metodoM1
di istanza . È necessario passare un'istanza quando viene richiamato il delegato.Viene creato un delegato di tipo
D2
, che rappresenta un metodo statico aperto, per il metodoM2
statico .
using System;
using System.Reflection;
using System.Security.Permissions;
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
//
public delegate void D1(C c, string s);
public delegate void D2(string s);
public delegate void D3();
// A sample class with an instance method and a static method.
//
public class C
{
private int id;
public C(int id) { this.id = id; }
public void M1(string s)
{
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}",
this.id, s);
}
public static void M2(string s)
{
Console.WriteLine("Static method M2 on C: s = {0}", s);
}
}
public class Example
{
public static void Main()
{
C c1 = new C(42);
// Get a MethodInfo for each method.
//
MethodInfo mi1 = typeof(C).GetMethod("M1",
BindingFlags.Public | BindingFlags.Instance);
MethodInfo mi2 = typeof(C).GetMethod("M2",
BindingFlags.Public | BindingFlags.Static);
D1 d1;
D2 d2;
D3 d3;
Console.WriteLine("\nAn instance method closed over C.");
// In this case, the delegate and the
// method must have the same list of argument types; use
// delegate type D2 with instance method M1.
//
Delegate test =
Delegate.CreateDelegate(typeof(D2), c1, mi1, false);
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
//
if (test != null)
{
d2 = (D2) test;
// The same instance of C is used every time the
// delegate is invoked.
d2("Hello, World!");
d2("Hi, Mom!");
}
Console.WriteLine("\nAn open instance method.");
// In this case, the delegate has one more
// argument than the instance method; this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
//
d1 = (D1) Delegate.CreateDelegate(typeof(D1), null, mi1);
// An instance of C must be passed in each time the
// delegate is invoked.
//
d1(c1, "Hello, World!");
d1(new C(5280), "Hi, Mom!");
Console.WriteLine("\nAn open static method.");
// In this case, the delegate and the method must
// have the same list of argument types; use delegate type
// D2 with static method M2.
//
d2 = (D2) Delegate.CreateDelegate(typeof(D2), null, mi2);
// No instances of C are involved, because this is a static
// method.
//
d2("Hello, World!");
d2("Hi, Mom!");
Console.WriteLine("\nA static method closed over the first argument (String).");
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
//
d3 = (D3) Delegate.CreateDelegate(typeof(D3),
"Hello, World!", mi2);
// Each time the delegate is invoked, the same string is
// used.
d3();
}
}
/* This code example produces the following output:
An instance method closed over C.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 42, s = Hi, Mom!
An open instance method.
Instance method M1 on C: id = 42, s = Hello, World!
Instance method M1 on C: id = 5280, s = Hi, Mom!
An open static method.
Static method M2 on C: s = Hello, World!
Static method M2 on C: s = Hi, Mom!
A static method closed over the first argument (String).
Static method M2 on C: s = Hello, World!
*/
open System
open System.Reflection
// A sample class with an instance method and a static method.
type C(id) =
member _.M1(s) =
printfn $"Instance method M1 on C: id = %i{id}, s = %s{s}"
static member M2(s) =
printfn $"Static method M2 on C: s = %s{s}"
// Declare three delegate types for demonstrating the combinations
// of static versus instance methods and open versus closed
// delegates.
type D1 = delegate of C * string -> unit
type D2 = delegate of string -> unit
type D3 = delegate of unit -> unit
let c1 = C 42
// Get a MethodInfo for each method.
//
let mi1 = typeof<C>.GetMethod("M1", BindingFlags.Public ||| BindingFlags.Instance)
let mi2 = typeof<C>.GetMethod("M2", BindingFlags.Public ||| BindingFlags.Static)
printfn "\nAn instance method closed over C."
// In this case, the delegate and the
// method must have the same list of argument types use
// delegate type D2 with instance method M1.
let test = Delegate.CreateDelegate(typeof<D2>, c1, mi1, false)
// Because false was specified for throwOnBindFailure
// in the call to CreateDelegate, the variable 'test'
// contains null if the method fails to bind (for
// example, if mi1 happened to represent a method of
// some class other than C).
if test <> null then
let d2 = test :?> D2
// The same instance of C is used every time the
// delegate is invoked.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nAn open instance method."
// In this case, the delegate has one more
// argument than the instance method this argument comes
// at the beginning, and represents the hidden instance
// argument of the instance method. Use delegate type D1
// with instance method M1.
let d1 = Delegate.CreateDelegate(typeof<D1>, null, mi1) :?> D1
// An instance of C must be passed in each time the
// delegate is invoked.
d1.Invoke(c1, "Hello, World!")
d1.Invoke(C 5280, "Hi, Mom!")
printfn "\nAn open static method."
// In this case, the delegate and the method must
// have the same list of argument types use delegate type
// D2 with static method M2.
let d2 = Delegate.CreateDelegate(typeof<D2>, null, mi2) :?> D2
// No instances of C are involved, because this is a static
// method.
d2.Invoke "Hello, World!"
d2.Invoke "Hi, Mom!"
printfn "\nA static method closed over the first argument (String)."
// The delegate must omit the first argument of the method.
// A string is passed as the firstArgument parameter, and
// the delegate is bound to this string. Use delegate type
// D3 with static method M2.
let d3 = Delegate.CreateDelegate(typeof<D3>, "Hello, World!", mi2) :?> D3
// Each time the delegate is invoked, the same string is used.
d3.Invoke()
// This code example produces the following output:
// An instance method closed over C.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 42, s = Hi, Mom!
//
// An open instance method.
// Instance method M1 on C: id = 42, s = Hello, World!
// Instance method M1 on C: id = 5280, s = Hi, Mom!
//
// An open static method.
// Static method M2 on C: s = Hello, World!
// Static method M2 on C: s = Hi, Mom!
//
// A static method closed over the first argument (String).
// Static method M2 on C: s = Hello, World!
Imports System.Reflection
Imports System.Security.Permissions
' Declare three delegate types for demonstrating the combinations
' of Shared versus instance methods and open versus closed
' delegates.
'
Public Delegate Sub D1(ByVal c As C, ByVal s As String)
Public Delegate Sub D2(ByVal s As String)
Public Delegate Sub D3()
' A sample class with an instance method and a Shared method.
'
Public Class C
Private id As Integer
Public Sub New(ByVal id As Integer)
Me.id = id
End Sub
Public Sub M1(ByVal s As String)
Console.WriteLine("Instance method M1 on C: id = {0}, s = {1}", _
Me.id, s)
End Sub
Public Shared Sub M2(ByVal s As String)
Console.WriteLine("Shared method M2 on C: s = {0}", s)
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim c1 As New C(42)
' Get a MethodInfo for each method.
'
Dim mi1 As MethodInfo = GetType(C).GetMethod("M1", _
BindingFlags.Public Or BindingFlags.Instance)
Dim mi2 As MethodInfo = GetType(C).GetMethod("M2", _
BindingFlags.Public Or BindingFlags.Static)
Dim d1 As D1
Dim d2 As D2
Dim d3 As D3
Console.WriteLine(vbLf & "An instance method closed over C.")
' In this case, the delegate and the
' method must have the same list of argument types; use
' delegate type D2 with instance method M1.
'
Dim test As [Delegate] = _
[Delegate].CreateDelegate(GetType(D2), c1, mi1, False)
' Because False was specified for throwOnBindFailure
' in the call to CreateDelegate, the variable 'test'
' contains Nothing if the method fails to bind (for
' example, if mi1 happened to represent a method of
' some class other than C).
'
If test IsNot Nothing Then
d2 = CType(test, D2)
' The same instance of C is used every time the
' delegate is invoked.
d2("Hello, World!")
d2("Hi, Mom!")
End If
Console.WriteLine(vbLf & "An open instance method.")
' In this case, the delegate has one more
' argument than the instance method; this argument comes
' at the beginning, and represents the hidden instance
' argument of the instance method. Use delegate type D1
' with instance method M1.
'
d1 = CType([Delegate].CreateDelegate(GetType(D1), Nothing, mi1), D1)
' An instance of C must be passed in each time the
' delegate is invoked.
'
d1(c1, "Hello, World!")
d1(New C(5280), "Hi, Mom!")
Console.WriteLine(vbLf & "An open Shared method.")
' In this case, the delegate and the method must
' have the same list of argument types; use delegate type
' D2 with Shared method M2.
'
d2 = CType([Delegate].CreateDelegate(GetType(D2), Nothing, mi2), D2)
' No instances of C are involved, because this is a Shared
' method.
'
d2("Hello, World!")
d2("Hi, Mom!")
Console.WriteLine(vbLf & "A Shared method closed over the first argument (String).")
' The delegate must omit the first argument of the method.
' A string is passed as the firstArgument parameter, and
' the delegate is bound to this string. Use delegate type
' D3 with Shared method M2.
'
d3 = CType([Delegate].CreateDelegate(GetType(D3), "Hello, World!", mi2), D3)
' Each time the delegate is invoked, the same string is
' used.
d3()
End Sub
End Class
' This code example produces the following output:
'
'An instance method closed over C.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C: id = 42, s = Hello, World!
'Instance method M1 on C: id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C: s = Hello, World!
'Shared method M2 on C: s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C: s = Hello, World!
'
Esempio 2
Nell'esempio di codice seguente viene illustrata la compatibilità dei tipi di parametro e dei tipi restituiti.
L'esempio di codice definisce una classe di base denominata Base
e una classe denominata Derived
che deriva da Base
. La classe derivata ha un static
metodo (Shared
in Visual Basic) denominato MyMethod
con un parametro di tipo Base
e un tipo restituito di Derived
. L'esempio di codice definisce anche un delegato denominato Example
con un parametro di tipo Derived
e un tipo restituito di Base
.
Nell'esempio di codice viene illustrato che il delegato denominato Example
può essere usato per rappresentare il metodo MyMethod
. Il metodo può essere associato al delegato perché:
Il tipo di parametro del delegato (
Derived
) è più restrittivo del tipo di parametro (Base
MyMethod
), in modo che sia sempre sicuro passare l'argomento del delegato aMyMethod
.Il tipo restituito di
MyMethod
(Derived
) è più restrittivo del tipo di parametro del delegato (Base
), in modo che sia sempre sicuro eseguire il cast del tipo restituito del metodo al tipo restituito del delegato.
L'esempio di codice non produce alcun output.
using namespace System;
using namespace System::Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public ref class Base {};
public ref class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public:
static Derived^ MyMethod(Base^ arg)
{
Base^ dummy = arg;
return gcnew Derived();
}
};
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base^ Example(Derived^ arg);
void main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags::Public | BindingFlags::Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo^ minfo = Derived::typeid->GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example^ ex =
(Example^) Delegate::CreateDelegate(Example::typeid, minfo);
// Execute MyMethod using the delegate Example.
//
Base^ b = ex(gcnew Derived());
}
using System;
using System.Reflection;
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
//
public class Base {}
public class Derived : Base
{
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
//
public static Derived MyMethod(Base arg)
{
Base dummy = arg;
return new Derived();
}
}
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
//
public delegate Base Example(Derived arg);
class Test
{
public static void Main()
{
// The binding flags needed to retrieve MyMethod.
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
// Get a MethodInfo that represents MyMethod.
MethodInfo minfo = typeof(Derived).GetMethod("MyMethod", flags);
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example ex =
(Example) Delegate.CreateDelegate(typeof(Example), minfo);
// Execute MyMethod using the delegate Example.
//
Base b = ex(new Derived());
}
}
open System
open System.Reflection
// Define two classes to use in the demonstration, a base class and
// a class that derives from it.
type Base() = class end
type Derived() =
inherit Base()
// Define a static method to use in the demonstration. The method
// takes an instance of Base and returns an instance of Derived.
// For the purposes of the demonstration, it is not necessary for
// the method to do anything useful.
static member MyMethod(arg: Base) =
Derived()
// Define a delegate that takes an instance of Derived and returns an
// instance of Base.
type Example = delegate of Derived -> Base
// The binding flags needed to retrieve MyMethod.
let flags = BindingFlags.Public ||| BindingFlags.Static
// Get a MethodInfo that represents MyMethod.
let minfo = typeof<Derived>.GetMethod("MyMethod", flags)
// Demonstrate contravariance of parameter types and covariance
// of return types by using the delegate Example to represent
// MyMethod. The delegate binds to the method because the
// parameter of the delegate is more restrictive than the
// parameter of the method (that is, the delegate accepts an
// instance of Derived, which can always be safely passed to
// a parameter of type Base), and the return type of MyMethod
// is more restrictive than the return type of Example (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
let ex = Delegate.CreateDelegate(typeof<Example>, minfo) :?> Example
// Execute MyMethod using the delegate Example.
let b = Derived() |> ex.Invoke
Imports System.Reflection
' Define two classes to use in the demonstration, a base class and
' a class that derives from it.
'
Public Class Base
End Class
Public Class Derived
Inherits Base
' Define a Shared method to use in the demonstration. The method
' takes an instance of Base and returns an instance of Derived.
' For the purposes of the demonstration, it is not necessary for
' the method to do anything useful.
'
Public Shared Function MyMethod(ByVal arg As Base) As Derived
Dim dummy As Base = arg
Return New Derived()
End Function
End Class
' Define a delegate that takes an instance of Derived and returns an
' instance of Base.
'
Public Delegate Function Example(ByVal arg As Derived) As Base
Module Test
Sub Main()
' The binding flags needed to retrieve MyMethod.
Dim flags As BindingFlags = _
BindingFlags.Public Or BindingFlags.Static
' Get a MethodInfo that represents MyMethod.
Dim minfo As MethodInfo = _
GetType(Derived).GetMethod("MyMethod", flags)
' Demonstrate contravariance of parameter types and covariance
' of return types by using the delegate Example to represent
' MyMethod. The delegate binds to the method because the
' parameter of the delegate is more restrictive than the
' parameter of the method (that is, the delegate accepts an
' instance of Derived, which can always be safely passed to
' a parameter of type Base), and the return type of MyMethod
' is more restrictive than the return type of Example (that
' is, the method returns an instance of Derived, which can
' always be safely cast to type Base).
'
Dim ex As Example = CType( _
[Delegate].CreateDelegate(GetType(Example), minfo), _
Example _
)
' Execute MyMethod using the delegate Example.
'
Dim b As Base = ex(New Derived())
End Sub
End Module
Commenti
In .NET Framework versione 1.0 e 1.1 questo overload del metodo crea delegati solo per i metodi statici. In .NET Framework versione 2.0 questo overload del metodo può anche creare delegati del metodo open instance; ovvero delegati che forniscono in modo esplicito il primo argomento nascosto dei metodi di istanza. Per una spiegazione dettagliata, vedere l'overload del metodo più generale CreateDelegate(Type, Object, MethodInfo) , che consente di creare tutte le combinazioni di delegati aperti o chiusi per esempio o metodi statici e, facoltativamente, per specificare un primo argomento.
Nota
Questo overload del metodo deve essere usato quando il delegato non viene chiuso sul primo argomento, perché è leggermente più veloce in questo caso.
Questo overload del metodo equivale a chiamare l'overload del CreateDelegate(Type, MethodInfo, Boolean) metodo e specificare true
per throwOnBindFailure
.
Nota
A partire da .NET Framework 2.0 Service Pack 1, questo metodo può essere usato per accedere a metodi non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei metodi non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per la reflection.
Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.
Tipi di parametri compatibili e tipo restituito
In .NET Framework versione 2.0 i tipi di parametro e il tipo restituito di un delegato creato con questo overload del metodo devono essere compatibili con i tipi di parametro e il tipo restituito del metodo rappresentato dal delegato; i tipi non devono corrispondere esattamente. Rappresenta un rilassamento del comportamento di associazione in .NET Framework versione 1.0 e 1.1, in cui i tipi devono corrispondere esattamente.
Un parametro di un delegato è compatibile con il parametro di un metodo corrispondente se il tipo del parametro del delegato è più restrittivo rispetto al tipo del parametro del metodo. In questo modo si garantisce che un argomento passato al delegato possa essere passato in modo sicuro al metodo.
Analogamente, il tipo restituito di un delegato è compatibile con il tipo restituito di un metodo se il tipo restituito del metodo è più restrittivo rispetto al tipo restituito del delegato. In questo modo si garantisce la possibilità di eseguire in modo sicuro il cast del valore restituito del metodo nel tipo restituito del delegato.
Ad esempio, un delegato con un parametro di tipo Hashtable e un tipo restituito di Object può rappresentare un metodo con un parametro di tipo Object e un valore restituito di tipo Hashtable.