Delegate Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Representa um delegado, que é uma estrutura de dados que se refere a um método estático ou a uma instância de classe e a um método de instância dessa classe.
public ref class Delegate abstract
public ref class Delegate abstract : ICloneable, System::Runtime::Serialization::ISerializable
public abstract class Delegate
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, System.Runtime.Serialization.ISerializable
type Delegate = class
type Delegate = class
interface ICloneable
interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
type Delegate = class
interface ICloneable
interface ISerializable
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Delegate = class
interface ICloneable
interface ISerializable
Public MustInherit Class Delegate
Public MustInherit Class Delegate
Implements ICloneable, ISerializable
- Herança
-
Delegate
- Derivado
- Atributos
- Implementações
Exemplos
Esta seção contém dois exemplos de código. O primeiro exemplo demonstra os dois tipos de delegados que podem ser criados com esta sobrecarga de método: um delegado aberto sobre um método de instância e um delegado aberto sobre um método estático.
O segundo exemplo de código demonstra tipos de parâmetros compatíveis e tipos de retorno.
Exemplo 1
O exemplo de código a seguir demonstra as duas maneiras como um delegado pode ser criado usando essa sobrecarga do método CreateDelegate.
Note
Há duas sobrecargas do método CreateDelegate que especificam um MethodInfo, mas não um primeiro argumento; a sua funcionalidade é a mesma, exceto que uma permite especificar se deve lançar uma exceção em caso de falha ao vincular, e a outra sempre lança uma exceção. Este exemplo de código usa ambas as sobrecargas.
O exemplo declara uma classe C com um método estático M2 e um método de instância M1, e dois tipos delegados: D1 usa uma instância de C e uma cadeia de caracteres e D2 usa uma cadeia de caracteres.
Uma segunda classe chamada Example contém o código que cria os delegados.
- Um delegado do tipo
D1, representando um método de instância aberta, é criado para o método de instânciaM1. Uma instância deve ser passada quando o delegado é invocado. - Um delegado do tipo
D2, representando um método estático aberto, é criado para o método estáticoM2.
using System;
using System.Reflection;
// 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 = {this.id}, s = {s}");
public static void M2(string s)
{
Console.WriteLine($"Static method M2 on C: s = {s}");
}
}
public class Example2
{
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 C2, 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 C2
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 C2: id = {0}, s = {1}",
Me.id, s)
End Sub
Public Shared Sub M2(ByVal s As String)
Console.WriteLine("Shared method M2 on C2: s = {0}", s)
End Sub
End Class
Public Class Example2
Public Shared Sub Main()
Dim c1 As New C2(42)
' Get a MethodInfo for each method.
'
Dim mi1 As MethodInfo = GetType(C2).GetMethod("M1",
BindingFlags.Public Or BindingFlags.Instance)
Dim mi2 As MethodInfo = GetType(C2).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 C2.")
' 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 C2).
'
If test IsNot Nothing Then
d2 = CType(test, D2)
' The same instance of C2 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 C2 must be passed in each time the
' delegate is invoked.
'
d1(c1, "Hello, World!")
d1(New C2(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 C2 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 C2.
'Instance method M1 on C2: id = 42, s = Hello, World!
'Instance method M1 on C2: id = 42, s = Hi, Mom!
'
'An open instance method.
'Instance method M1 on C2: id = 42, s = Hello, World!
'Instance method M1 on C2: id = 5280, s = Hi, Mom!
'
'An open Shared method.
'Shared method M2 on C2: s = Hello, World!
'Shared method M2 on C2: s = Hi, Mom!
'
'A Shared method closed over the first argument (String).
'Shared method M2 on C2: s = Hello, World!
'
Exemplo 2
O exemplo de código a seguir demonstra a compatibilidade de tipos de parâmetros e tipos de retorno.
O exemplo de código define uma classe base chamada Base e uma classe chamada Derived que deriva de Base. A classe derivada tem um método static (Shared no Visual Basic) chamado MyMethod com um parâmetro do tipo Base e um tipo de retorno de Derived. O exemplo de código também define um delegado chamado Example que tem um parâmetro do tipo Derived e um tipo de retorno de Base.
O exemplo de código demonstra que o delegado chamado Example pode ser usado para representar o método MyMethod. O método pode ser vinculado ao delegado porque:
- O tipo de parâmetro do delegado (
Derived) é mais restritivo do que o tipo de parâmetro deMyMethod(Base), de modo que é sempre seguro passar o argumento do delegado paraMyMethod. - O tipo de retorno de
MyMethod(Derived) é mais restritivo do que o tipo de parâmetro do delegado (Base), de modo que é sempre seguro converter o tipo de retorno do método para o tipo de retorno do delegado.
O exemplo de código não produz nenhuma saída.
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 Example5(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 Example5 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 Example5 (that
// is, the method returns an instance of Derived, which can
// always be safely cast to type Base).
//
Example5 ex =
(Example5)Delegate.CreateDelegate(typeof(Example5), minfo);
// Execute MyMethod using the delegate Example5.
//
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
métodos CreateDelegate(Type, Object, MethodInfo) e CreateDelegate(Type, Object, MethodInfo, Boolean)
A funcionalidade dessas duas sobrecargas é a mesma, exceto que uma permite que você especifique se deve lançar em falha para vincular, e a outra sempre lança.
O tipo de delegado e o método devem ter tipos de retorno compatíveis. Ou seja, o tipo de retorno de method deve ser atribuível ao tipo de retorno de type.
firstArgument, o segundo parâmetro para essas sobrecargas, é o primeiro argumento do método que o delegado representa. Se firstArgument for fornecida, ela será passada para method toda vez que o delegado for invocado; firstArgument é dito estar vinculado ao delegado, e o delegado é dito estar fechado sobre seu primeiro argumento. Se method for static (Shared no Visual Basic), a lista de argumentos fornecida ao invocar o delegado inclui todos os parâmetros, exceto o primeiro; se method for um método de instância, firstArgument será passado para o parâmetro de instância oculta (representado por this em C# ou por Me no Visual Basic).
Se firstArgument for fornecida, o primeiro parâmetro de method deve ser um tipo de referência e firstArgument deve ser compatível com esse tipo.
Importante
Se method é static (Shared no Visual Basic) e seu primeiro parâmetro é do tipo Object ou ValueType, então firstArgument pode ser um tipo de valor. Neste caso, firstArgument é automaticamente encaixotado. O encaixotamento automático não ocorre para outros argumentos, como seria numa chamada de função C# ou Visual Basic.
Se firstArgument é uma referência nula e method é um método de instância, o resultado depende das assinaturas do tipo delegado type e de method:
- Se a assinatura de
typeincluir explicitamente o primeiro parâmetro oculto demethod, o delegado representará um método de instância aberta. Quando o delegado é invocado, o primeiro argumento na lista de argumentos é passado para o parâmetro de instância oculta demethod. - Se as assinaturas de
methodetypecorresponderem (ou seja, todos os tipos de parâmetros são compatíveis), então diz-se que o delegado está associado a uma referência nula. Invocar o delegado é como chamar um método de instância em uma instância nula, o que não é uma coisa particularmente útil a fazer.
Se firstArgument é uma referência nula e method é estática, o resultado depende das assinaturas do tipo delegado type e de method:
- Se a assinatura de
methodetypecorresponderem (ou seja, todos os tipos de parâmetros são compatíveis), diz-se que o delegado representa um método estático aberto. Este é o caso mais comum para métodos estáticos. Nesse caso, você pode obter um desempenho ligeiramente melhor usando a sobrecarga de método CreateDelegate(Type, MethodInfo). - Se a assinatura de
typecomeça com o segundo parâmetro demethode os restantes tipos de parâmetros são compatíveis, diz-se que o delegado está fechado sobre uma referência nula. Quando o delegado é invocado, uma referência nula é passada para o primeiro parâmetro demethod.
Exemplo
O exemplo de código a seguir mostra todos os métodos que um único tipo de delegado pode representar: fechado sobre um método de instância, aberto sobre um método de instância, aberto sobre um método estático e fechado sobre um método estático.
O exemplo de código define duas classes, C e F, e um tipo delegado D com um argumento do tipo C. As classes têm métodos estáticos e de instância correspondentes M1, M3e M4, e a classe C também tem um método de instância M2 que não tem argumentos.
Uma terceira classe chamada Example contém o código que cria os delegados.
- Os delegados são criados para o método de instância
M1do tipoCe do tipoF; cada um é associado a uma instância do respetivo tipo. O métodoM1do tipoCexibe as propriedadesIDda instância acoplada e do argumento. - Um delegado é criado para o método
M2do tipoC. Este é um delegado de instância aberta, no qual o argumento do delegado representa o primeiro argumento oculto no método de instância. O método não tem outros argumentos. É chamado como se fosse um método estático. - Os delegados são criados para o método estático
M3do tipoCe tipoF; estes são delegados estáticos abertos. - Finalmente, são criados delegados para o método estático
M4do tipoCe do tipoF; cada método tem o tipo de declaração como seu primeiro argumento, e uma instância do tipo é fornecida, para que os delegados fiquem fechados sobre os seus primeiros argumentos. O métodoM4do tipoCexibe as propriedadesIDda instância acoplada e do argumento.
using System;
using System.Reflection;
// 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(C1 c);
// Declare two sample classes, C1 and F. Class C1 has an ID
// property so instances can be identified.
//
public class C1
{
private int id;
public int ID => id;
public C1(int id) => this.id = id;
public void M1(C1 c)
{
Console.WriteLine("Instance method M1(C1 c) on C1: this.id = {0}, c.ID = {1}",
this.id, c.ID);
}
public void M2()
{
Console.WriteLine($"Instance method M2() on C1: this.id = {this.id}");
}
public static void M3(C1 c)
{
Console.WriteLine($"Static method M3(C1 c) on C1: c.ID = {c.ID}");
}
public static void M4(C1 c1, C1 c2)
{
Console.WriteLine("Static method M4(C1 c1, C1 c2) on C1: c1.ID = {0}, c2.ID = {1}",
c1.ID, c2.ID);
}
}
public class F
{
public void M1(C1 c)
{
Console.WriteLine($"Instance method M1(C1 c) on F: c.ID = {c.ID}");
}
public static void M3(C1 c)
{
Console.WriteLine($"Static method M3(C1 c) on F: c.ID = {c.ID}");
}
public static void M4(F f, C1 c)
{
Console.WriteLine($"Static method M4(F f, C1 c) on F: c.ID = {c.ID}");
}
}
public class Example
{
public static void Main()
{
C1 c1 = new (42);
C1 c2 = new (1491);
F f1 = new ();
D d;
// Instance method with one argument of type C1.
MethodInfo cmi1 = typeof(C1).GetMethod("M1");
// Instance method with no arguments.
MethodInfo cmi2 = typeof(C1).GetMethod("M2");
// Static method with one argument of type C1.
MethodInfo cmi3 = typeof(C1).GetMethod("M3");
// Static method with two arguments of type C1.
MethodInfo cmi4 = typeof(C1).GetMethod("M4");
// Instance method with one argument of type C1.
MethodInfo fmi1 = typeof(F).GetMethod("M1");
// Static method with one argument of type C1.
MethodInfo fmi3 = typeof(F).GetMethod("M3");
// Static method with an argument of type F and an argument
// of type C1.
MethodInfo fmi4 = typeof(F).GetMethod("M4");
Console.WriteLine("\nAn instance method on any type, with an argument of type C1.");
// D can represent any instance method that exactly matches its
// signature. Methods on C1 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 C1 with no arguments.");
// D can represent an instance method on C1 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 C1 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 C1.");
// D can represent any static method with the same signature.
// Methods on F and C1 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 C1.");
// D can represent any static method with one argument of the
// type the method belongs and a second argument of type C1.
// 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 C1 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 C1.
Instance method M1(C1 c) on C1: this.id = 42, c.ID = 1491
Instance method M1(C1 c) on F: c.ID = 1491
An instance method on C1 with no arguments.
Instance method M2() on C1: this.id = 42
A static method on any type, with an argument of type C1.
Static method M3(C1 c) on C1: c.ID = 42
Static method M3(C1 c) on F: c.ID = 42
A static method on any type, with an argument of
that type and an argument of type C1.
Static method M4(C1 c1, C1 c2) on C1: c1.ID = 42, c2.ID = 1491
Static method M4(F f, C1 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 Example5
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
'
Tipos de parâmetros compatíveis e tipo de retorno
Os tipos de parâmetros e o tipo de retorno de um delegado criado usando essa sobrecarga de método devem ser compatíveis com os tipos de parâmetros e o tipo de retorno do método que o delegado representa; os tipos não têm de corresponder exatamente.
Um parâmetro de um delegado é compatível com o parâmetro correspondente de um método se o tipo do parâmetro delegate for mais restritivo do que o tipo do parâmetro method, porque isso garante que um argumento passado para o delegado possa ser passado com segurança para o método.
Da mesma forma, o tipo de retorno de um delegado é compatível com o tipo de retorno de um método se o tipo de retorno do método for mais restritivo do que o tipo de retorno do delegado, porque isso garante que o valor de retorno do método possa ser convertido com segurança para o tipo de retorno do delegado.
Por exemplo, um delegado com um parâmetro do tipo Hashtable e um tipo de retorno de Object pode representar um método com um parâmetro do tipo Object e um valor de retorno do tipo Hashtable.
Determinar os métodos que um delegado pode representar
Outra maneira útil de pensar na flexibilidade fornecida pela sobrecarga de CreateDelegate(Type, Object, MethodInfo) é que qualquer delegado pode representar quatro combinações diferentes de assinatura de método e tipo de método (estático versus instância). Considere um tipo de delegado D com um único argumento do tipo C. A seguir descrevemos os métodos que D pode representar, ignorando o tipo de retorno, uma vez que ele deve corresponder em todos os casos:
Dpode representar qualquer método de instância que tenha exatamente um argumento do tipoC, independentemente do tipo ao qual o método de instância pertence. Quando CreateDelegate é chamado,firstArgumenté uma instância do tipo ao qualmethodpertence, e o delegado resultante é considerado fechado em torno dessa instância. (Trivialmente,Dtambém pode ser fechado sobre uma referência nula sefirstArgumentfor uma referência nula.)Dpode representar um método de instância deCque não tem argumentos. Quando CreateDelegate é chamado,firstArgumenté uma referência nula. O delegado resultante representa um método de instância aberta, e uma instância deCdeve ser fornecida sempre que o método é invocado.Dpode representar um método estático que usa um argumento do tipoC, e esse método pode pertencer a qualquer tipo. Quando CreateDelegate é chamado,firstArgumenté uma referência nula. O delegado resultante representa um método estático aberto, e uma instância deCdeve ser fornecida cada vez que é invocada.Dpode representar um método estático que pertence ao tipoFe tem dois argumentos, de tipoFe tipoC. Quando CreateDelegate é chamado,firstArgumenté uma instância deF. O delegado resultante representa um método estático que é fechado sobre essa instância deF. Observe que, no caso em queFeCsão do mesmo tipo, o método estático tem dois argumentos desse tipo. (Nesse caso,Dé encerrado por uma referência nula sefirstArgumentfor uma referência nula.)
Observações
A Delegate classe é a classe base para os tipos de delegados. No entanto, apenas o sistema e os compiladores podem derivar explicitamente da Delegate classe ou da classe MulticastDelegate . Também não é permitido derivar um novo tipo a partir de um tipo delegado. A Delegate classe não é considerada um tipo de delegado; é uma classe usada para derivar tipos de delegados.
A maioria das linguagens implementa uma delegate palavra-chave, e os compiladores dessas linguagens conseguem derivar da MulticastDelegate classe; por isso, os utilizadores devem usar a delegate palavra-chave fornecida pela língua.
Note
O runtime da linguagem comum fornece um Invoke método para cada tipo de delegado, com a mesma assinatura do delegado. Não tens de chamar este método explicitamente de C# ou Visual Basic porque os compiladores chamam-no automaticamente. O Invoke método é útil na reflexão quando se quer encontrar a assinatura do tipo de delegado.
O runtime da linguagem comum fornece a cada tipo de delegado e BeginInvokeEndInvoke métodos, permitindo a invocação assíncrona do delegado. Para mais informações sobre estes métodos, veja Chamar Métodos Síncronos Assíncronos.
A declaração de um tipo de delegado estabelece um contrato que especifica a assinatura de um ou mais métodos. Um delegado é uma instância do tipo delegado que tem referências a:
- Um método de instância de um tipo e um objeto alvo atribuível a esse tipo.
- Um método de instância de um tipo, com o parâmetro oculto
thisexposto na lista formal de parâmetros. Diz-se que o delegado é um delegado de instância aberta. - Um método estático.
- Um método estático e um objeto alvo atribuível ao primeiro parâmetro do método. Diz-se que o delegado está fechado quanto ao seu primeiro argumento.
Para mais informações sobre a ligação de delegados, veja a CreateDelegate(Type, Object, MethodInfo, Boolean) sobrecarga de métodos.
Quando um delegado representa um método de instância fechado sobre o seu primeiro argumento (o caso mais comum), o delegado armazena uma referência ao ponto de entrada do método e uma referência a um objeto, chamado destino, que é de um tipo atribuível ao tipo que definiu o método. Quando um delegado representa um método de instância aberta, armazena uma referência ao ponto de entrada do método. A assinatura do delegado deve incluir o parâmetro oculto this na sua lista formal de parâmetros; neste caso, o delegado não tem referência a um objeto alvo, e um objeto alvo deve ser fornecido quando o delegado é invocado.
Quando um delegado representa um método estático, o delegado armazena uma referência ao ponto de entrada do método. Quando um delegado representa um método estático fechado sobre o seu primeiro argumento, o delegado armazena uma referência ao ponto de entrada do método e uma referência a um objeto alvo atribuível ao tipo do primeiro argumento do método. Quando o delegado é invocado, o primeiro argumento do método estático recebe o objeto alvo. Este primeiro argumento deve ser um tipo de referência.
A lista de invocação de um delegado é um conjunto ordenado de delegados em que cada elemento da lista invoca exatamente um dos métodos representados pelo delegado. Uma lista de invocações pode conter métodos duplicados. Durante uma invocação, os métodos são invocados pela ordem em que aparecem na lista de invocações. Um delegado tenta invocar todos os métodos da sua lista de invocações; Os duplicados são invocados uma vez por cada vez que aparecem na lista de invocações. Os delegados são imutáveis; Uma vez criada, a lista de invocações de um delegado não muda.
Os delegados são designados por multicast, ou combináveis, porque um delegado pode invocar um ou mais métodos e podem ser usados em operações de combinação.
Operações de combinação, como Combine e Remove, não alteram os delegados existentes. Em vez disso, tal operação devolve um novo delegado que contém os resultados da operação, um delegado inalterado, ou null. Uma operação de combinação retorna null quando o resultado da operação é um delegado que não faz referência a pelo menos um método. Uma operação de combinação devolve um delegado inalterado quando a operação solicitada não tem efeito.
Note
As linguagens geridas utilizam os Combine métodos e Remove para implementar operações de delegado. Exemplos incluem as instruções AddHandler e RemoveHandler em Visual Basic e os operadores += e -= nos tipos de delegados em C#.
Tipos genéricos de delegado podem ter parâmetros de tipo variantes. Parâmetros de tipo contravariante podem ser usados como tipos de parâmetros do delegado, e um parâmetro de tipo covariante pode ser usado como tipo de retorno. Esta funcionalidade permite que tipos genéricos de delegado construídos a partir da mesma definição genérica de tipo sejam compatíveis com atribuição se os seus argumentos de tipo forem tipos de referência com uma relação de herança, como explicado em Covariância e Contravariância.
Note
Delegados genéricos que são compatíveis com atribuição devido à variância não são necessariamente combináveis. Para serem combináveis, os tipos têm de coincidir exatamente. Por exemplo, suponha que uma classe nomeada Derived é derivada de uma classe nomeada Base. Um delegado de tipo Action<Base> (Action(Of Base) em Visual Basic) pode ser atribuído a uma variável do tipo Action<Derived>, mas os dois delegados não podem ser combinados porque os tipos não coincidem exatamente.
Se um método invocado lançar uma exceção, o método deixa de ser executado, a exceção é passada de volta ao chamador do delegado, e os métodos restantes na lista de invocação não são invocados. Apanhar a exceção no chamador não altera este comportamento.
Quando a assinatura dos métodos invocados por um delegado inclui um valor de retorno, o delegado devolve o valor de retorno do último elemento na lista de invocação. Quando a assinatura inclui um parâmetro que é passado por referência, o valor final do parâmetro é o resultado de cada método na lista de invocações a executar-se sequencialmente e a atualizar o valor do parâmetro.
O equivalente mais próximo de um delegado em C é um ponteiro de função. Um delegado pode representar um método estático ou um método de instância. Quando o delegado representa um método de instância, o delegado armazena não só uma referência ao ponto de entrada do método, mas também uma referência à instância da classe. Ao contrário dos ponteiros de função, os delegados são orientados a objetos e seguros para tipos.
Exemplos do CreateDelegate
Os métodos CreateDelegate criam um delegado de um tipo especificado.
CreateDelegate(Type, MethodInfo) método
Essa sobrecarga de método é equivalente a chamar a sobrecarga de método CreateDelegate(Type, MethodInfo, Boolean) e especificar true para throwOnBindFailure.
Construtores
| Name | Descrição |
|---|---|
| Delegate(Object, String) |
Inicializa um delegado que invoca o método de instância especificado na instância de classe especificada. |
| Delegate(Type, String) |
Inicializa um delegado que invoca o método estático especificado a partir da classe especificada. |
Propriedades
| Name | Descrição |
|---|---|
| HasSingleTarget |
Recebe um valor que indica se tem Delegate um único alvo de invocação. |
| Method |
Obtém o método representado pelo delegado. |
| Target |
Obtém a instância de classe em que o delegado atual invoca o método de instância. |
Métodos
| Name | Descrição |
|---|---|
| Clone() |
Cria uma cópia superficial do delegado. |
| Combine(Delegate, Delegate) |
Concatena as listas de invocações de dois delegados. |
| Combine(Delegate[]) |
Concatena as listas de invocações de um array de delegados. |
| Combine(ReadOnlySpan<Delegate>) |
Concatena as listas de invocações de um conjunto de delegados. |
| CombineImpl(Delegate) |
Concatena as listas de invocação do delegado multicast (combinável) especificado e do delegado multicast (combinável) atual. |
| CreateDelegate(Type, MethodInfo, Boolean) |
Cria um delegado do tipo especificado para representar o método estático especificado, com o comportamento especificado em caso de falha na ligação. |
| CreateDelegate(Type, MethodInfo) |
Cria um delegado do tipo especificado para representar o método especificado. |
| CreateDelegate(Type, Object, MethodInfo, Boolean) |
Cria um delegado do tipo especificado que representa o método estático ou de instância especificado, com o primeiro argumento especificado e o comportamento especificado em caso de falha em vinculação. |
| CreateDelegate(Type, Object, MethodInfo) |
Cria um delegado do tipo especificado que representa o método estático ou de instância especificado, com o primeiro argumento especificado. |
| CreateDelegate(Type, Object, String, Boolean, Boolean) |
Cria um delegado do tipo especificado que representa o método de instância especificado a invocar na instância de classe especificada, com a sensibilidade a maiúsculas e minúsculas especificadas e o comportamento especificado em caso de falha em vinculação. |
| CreateDelegate(Type, Object, String, Boolean) |
Cria um delegado do tipo especificado que representa o método de instância especificado para invocar na instância de classe especificada com a sensibilidade a maiúsculas e minúsculas especificada. |
| CreateDelegate(Type, Object, String) |
Cria um delegado do tipo especificado que representa o método de instância especificado a invocar na instância de classe especificada. |
| CreateDelegate(Type, Type, String, Boolean, Boolean) |
Cria um delegado do tipo especificado que representa o método estático especificado da classe especificada, com a sensibilidade a maiúsculas e minúsculas especificadas e o comportamento especificado em caso de falha em vinculação. |
| CreateDelegate(Type, Type, String, Boolean) |
Cria um delegado do tipo especificado que representa o método estático especificado da classe especificada, com a sensibilidade a maiúsculas e minúsculas especificada. |
| CreateDelegate(Type, Type, String) |
Cria um delegado do tipo especificado que representa o método estático especificado da classe especificada. |
| DynamicInvoke(Object[]) |
Invoca dinamicamente (limite tardio) o método representado pelo delegado atual. |
| DynamicInvokeImpl(Object[]) |
Invoca dinamicamente (limite tardio) o método representado pelo delegado atual. |
| EnumerateInvocationList<TDelegate>(TDelegate) |
Obtém um enumerador para os alvos de invocação deste delegado. |
| Equals(Object) |
Determina se o objeto especificado e o delegado atual são do mesmo tipo e partilham os mesmos alvos, métodos e lista de invocações. |
| GetHashCode() |
Devolve um código de hash para o delegado. |
| GetInvocationList() |
Devolve a lista de invocações do delegado. |
| GetMethodImpl() |
Obtém o método representado pelo delegado atual. |
| GetObjectData(SerializationInfo, StreamingContext) |
Obsoleto.
Não suportado. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| Remove(Delegate, Delegate) |
Remove a última ocorrência da lista de invocações de um delegado da lista de invocações de outro delegado. |
| RemoveAll(Delegate, Delegate) |
Remove todas as ocorrências da lista de invocações de um delegado da lista de invocações de outro delegado. |
| RemoveImpl(Delegate) |
Remove a lista de invocações de um delegado da lista de invocações de outro delegado. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Operadores
| Name | Descrição |
|---|---|
| Equality(Delegate, Delegate) |
Determina se os delegados especificados são iguais. |
| Inequality(Delegate, Delegate) |
Determina se os delegados especificados não são iguais. |
Métodos da Extensão
| Name | Descrição |
|---|---|
| GetMethodInfo(Delegate) |
Obtém um objeto que representa o método representado pelo delegado especificado. |