Delegate Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
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 essa sobrecarga de método: aberto em um método de instância e aberto em um método estático.
O segundo exemplo de código demonstra tipos de parâmetro compatíveis e tipos de retorno.
Exemplo 1
O exemplo de código a seguir demonstra as duas maneiras pelas quais um delegado pode ser criado usando essa sobrecarga do CreateDelegate método.
Note
Há duas sobrecargas do método CreateDelegate que especificam um MethodInfo, mas não um primeiro argumento; sua funcionalidade é a mesma, exceto que uma permite que você especifique se uma exceção será gerada em caso de falha de vinculação e a outra sempre gera exceções. Este exemplo de código usa as duas sobrecargas.
O exemplo declara uma classe C com um método M2 estático e um método M1 de instância, e dois tipos de delegado: D1 usa uma instância de C e uma cadeia de caracteres, e D2 usa uma cadeia de caracteres.
Uma segunda classe nomeada 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 representante é invocado. - Um delegado do tipo
D2, que representa um método estático aberto, é criado para o métodoM2estático.
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âmetro e tipos de retorno.
O exemplo de código define uma classe base nomeada Base e uma classe chamada Derived que deriva de Base. A classe derivada tem um static método (Shared no Visual Basic) nomeado MyMethod com um parâmetro de 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 de tipo Derived e um tipo de retorno de Base.
O exemplo de código demonstra que o delegado nomeado Example pode ser usado para representar o método MyMethod. O método pode ser associado ao representante 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 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 deseja gerar uma falha na associação e a outra sempre é gerada.
O tipo 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 fornecido, ele será passado para method cada vez que o delegado é invocado; diz-se que firstArgument está vinculado ao delegado, e diz-se que o delegado está fechado em 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 oculto (representado por this no C# ou no Me Visual Basic).
Se firstArgument for fornecido, o primeiro parâmetro deve ser um tipo de method referência e firstArgument deve ser compatível com esse tipo.
Importante
Se method for static (Shared no Visual Basic) e seu primeiro parâmetro for de tipo Object ou ValueType, então firstArgument poderá ser um tipo de valor. Nesse caso, firstArgument é automaticamente empacotado. O empacotamento automático não ocorre para nenhum outro argumento, como ocorreria em uma chamada de função em C# ou Visual Basic.
Se firstArgument for uma referência nula e method for um método de instância, o resultado dependerá das assinaturas do tipo type delegado e de method:
- Se a assinatura de
typeincluir explicitamente o primeiro parâmetro oculto demethod, o delegado é considerado como representando 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
methodetypecoincidem (ou seja, todos os tipos de parâmetro são compatíveis), o delegado é considerado fechado sobre 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 de se fazer.
Se firstArgument for uma referência nula e method for estático, o resultado dependerá das assinaturas do tipo type delegado e de method:
- Se as assinaturas de
methodetypecorresponderem (ou seja, todos os tipos de parâmetro forem compatíveis), diz-se que o delegado representa um método estático aberto. Esse é o caso mais comum para métodos estáticos. Nesse caso, você pode obter um desempenho um pouco melhor usando a sobrecarga do método CreateDelegate(Type, MethodInfo). - Se a assinatura de
typecomeçar com o segundo parâmetro demethode o restante dos tipos de parâmetros forem compatíveis, então dizemos 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.
Example
O exemplo de código a seguir mostra todos os métodos que um único tipo de delegado pode representar: fechado em um método de instância, aberto em um método de instância, aberto em um método estático e fechado em 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 M4a classe C também tem um método M2 de instância que não tem argumentos.
Uma terceira classe nomeada Example contém o código que cria os delegados.
- Os delegados são criados para o método de instância
M1do tipoCe tipoF, cada um é fechado em uma instância do respectivo tipo. O métodoM1de tipoCexibe asIDpropriedades da instância associada e do argumento. - Um delegado é criado para o método
M2do tipoC. Esse é 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
M3estático de tipoCe tipoF; eles são delegados estáticos abertos. - Por fim, os delegados são criados para o método estático
M4dos tiposCeF; cada método tem o tipo declarador como seu primeiro argumento, e uma instância do tipo é fornecida, de modo que os delegados são fechados em relação a seus primeiros argumentos. O métodoM4de tipoCexibe asIDpropriedades da instância associada 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âmetro compatíveis e tipo de retorno
Os tipos de parâmetro e o tipo de retorno de um delegado criado usando essa sobrecarga de método devem ser compatíveis com os tipos de parâmetro e o tipo de retorno do método que o delegado representa; os tipos não precisam 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 delegado for mais restritivo do que o tipo do parâmetro de método, pois 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, pois isso garante que o valor retornado 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 de retorno 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 forma útil de entender a flexibilidade fornecida pela CreateDelegate(Type, Object, MethodInfo) sobrecarga é que qualquer delegado específico pode representar quatro combinações diferentes de assinatura de método e natureza de método (estático versus instância). Considere um tipo delegado D com um argumento do tipo C. O seguinte descreve que os métodos D podem representar, ignorando o tipo de retorno, pois ele deve corresponder em todos os casos:
Dpode representar qualquer método de instância que tenha exatamente um argumento de tipoC, independentemente do tipo ao qual o método de instância pertence. Quando CreateDelegate é chamado,firstArgumenté uma instância do tipo a quemethodpertence, e o delegado resultante é considerado fechado em relação a essa instância. (Trivialmente,Dtambém pode ser fechado por 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 for invocada.Dpode representar um método estático que usa um argumento do tipoCe 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 sempre que ele for invocado.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 casoFem que eCsão do mesmo tipo, o método estático tem dois argumentos desse tipo. (Nesse caso,Dé fechado sobre uma referência nula sefirstArgumentfor uma referência nula.)
Comentários
A Delegate classe é a classe base para tipos delegados. No entanto, somente o sistema e os compiladores podem derivar explicitamente da Delegate classe ou da MulticastDelegate classe. Também não é permitido derivar um novo tipo de um tipo delegado. A Delegate classe não é considerada um tipo delegado; é uma classe usada para derivar tipos de delegado.
A maioria dos idiomas implementa uma delegate palavra-chave e os compiladores para esses idiomas podem derivar da MulticastDelegate classe; portanto, os usuários devem usar a delegate palavra-chave fornecida pelo idioma.
Note
O common language runtime fornece um Invoke método para cada tipo de delegado, com a mesma assinatura que o delegado. Você não precisa chamar esse método explicitamente de C# ou Visual Basic porque os compiladores o chamam automaticamente. O Invoke método é útil na reflexão quando você deseja encontrar a assinatura do tipo delegado.
O common language runtime fornece cada tipo delegado e BeginInvokeEndInvoke métodos para habilitar a invocação assíncrona do delegado. Para obter mais informações sobre esses métodos, consulte Chamando métodos síncronos de forma assíncrona.
A declaração de um tipo delegado estabelece um contrato que especifica a assinatura de um ou mais métodos. Um delegado é uma instância de um tipo delegado que tem referências a:
- Um método de instância de um tipo e um objeto de destino atribuível a esse tipo.
- Um método de instância de um tipo, com o parâmetro oculto
thisexposto na lista de parâmetros formais. Diz-se que o delegado é um delegado de instância aberta. - Um método estático.
- Um método estático e um objeto de destino atribuível ao primeiro parâmetro do método. Diz-se que o delegado foi fechado por causa de seu primeiro argumento.
Para obter mais informações sobre a associação de delegados, consulte a sobrecarga do CreateDelegate(Type, Object, MethodInfo, Boolean) método.
Quando um delegado representa um método de instância fechado sobre 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 de 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, ele armazena uma referência ao ponto de entrada do método. A assinatura delegada deve incluir o parâmetro oculto this em sua lista de parâmetros formais; nesse caso, o delegado não tem uma referência a um objeto de destino e um objeto de destino 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 seu primeiro argumento, o delegado armazena uma referência ao ponto de entrada do método e uma referência a um objeto de destino 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 de destino. Esse primeiro argumento deve ser um tipo de referência.
A lista de invocação de um delegado é um conjunto ordenado de delegados no qual cada elemento da lista invoca exatamente um dos métodos representados pelo delegado. Uma lista de invocação pode conter métodos duplicados. Durante uma invocação, os métodos são invocados na ordem em que aparecem na lista de invocação. Um delegado tenta invocar todos os métodos em sua lista de invocação; as duplicatas são invocadas uma vez para cada vez que aparecem na lista de invocação. Delegados são imutáveis; depois de criada, a lista de invocação de um delegado não é alterada.
Os delegados são chamados de multicast ou combináveis, porque um delegado pode invocar um ou mais métodos e pode ser usado na combinação de operações.
A combinação de operações, como Combine e Remove, não altera os delegados existentes. Em vez disso, tal operação retorna 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 retorna um delegado inalterado quando a operação solicitada não tem efeito.
Note
Os idiomas gerenciados usam e os CombineRemove métodos para implementar operações delegadas. Os exemplos incluem as instruções AddHandler e RemoveHandler em Visual Basic e os operadores += e -= em tipos delegados em C#.
Tipos de delegado genéricos podem ter parâmetros de tipo variante. Parâmetros de tipo contravariante podem ser usados como tipos de parâmetro do delegado e um parâmetro de tipo covariante pode ser usado como o tipo de retorno. Esse recurso permite que tipos delegados genéricos que são construídos a partir da mesma definição de tipo genérico sejam compatíveis com atribuição se seus argumentos de tipo forem tipos de referência com uma relação de herança, conforme explicado em Covariância e Contravariância.
Note
Delegados genéricos compatíveis com atribuição devido à variação não são necessariamente combináveis. Para serem combináveis, os tipos devem corresponder exatamente. Por exemplo, suponha que uma classe nomeada Derived seja derivada de uma classe chamada Base. Um delegado do 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 correspondem exatamente.
Se um método invocado gerar uma exceção, o método interromperá a execução, a exceção será passada de volta para o chamador do delegado e os métodos restantes na lista de invocação não serão invocados. Capturar a exceção no chamador não altera esse comportamento.
Quando a assinatura dos métodos invocados por um delegado inclui um valor retornado, o delegado retorna o valor retornado 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ção sendo executado sequencialmente e atualizando 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 apenas uma referência ao ponto de entrada do método, mas também uma referência à instância de classe. Ao contrário dos ponteiros de função, os delegados são orientados a objetos e digitam com segurança.
Exemplos de CreateDelegate
Os CreateDelegate métodos criam um delegado de um tipo especificado.
método CreateDelegate(Type, MethodInfo)
Essa sobrecarga de método é equivalente a chamar a sobrecarga do método CreateDelegate(Type, MethodInfo, Boolean) e especificar true para throwOnBindFailure.
Construtores
| Nome | Description |
|---|---|
| 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 da classe especificada. |
Propriedades
| Nome | Description |
|---|---|
| HasSingleTarget |
Obtém um valor que indica se ele Delegate tem um único destino de invocação. |
| Method |
Obtém o método representado pelo delegado. |
| Target |
Obtém a instância de classe na qual o delegado atual invoca o método de instância. |
Métodos
| Nome | Description |
|---|---|
| Clone() |
Cria uma cópia superficial do delegado. |
| Combine(Delegate, Delegate) |
Concatena as listas de invocação de dois delegados. |
| Combine(Delegate[]) |
Concatena as listas de invocação de uma matriz de delegados. |
| Combine(ReadOnlySpan<Delegate>) |
Concatena as listas de invocação de um intervalo de delegados. |
| CombineImpl(Delegate) |
Concatena as listas de invocação do delegado multicast especificado (combinável) e do delegado multicast atual (combinável). |
| 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 ao associar. |
| 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 sobre a falha na associaçã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 ser invocado na instância de classe especificada, com a diferenciação de maiúsculas e minúsculas especificada e o comportamento especificado na falha de associação. |
| CreateDelegate(Type, Object, String, Boolean) |
Cria um delegado do tipo especificado que representa o método de instância especificado a ser invocado na instância de classe especificada com a diferenciação de 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 ser invocado 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 diferenciação de maiúsculas e minúsculas especificada e o comportamento especificado na falha de associaçã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 diferenciação de 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 (com limite tardio) o método representado pelo delegado atual. |
| DynamicInvokeImpl(Object[]) |
Invoca dinamicamente (com limite tardio) o método representado pelo delegado atual. |
| EnumerateInvocationList<TDelegate>(TDelegate) |
Obtém um enumerador para os destinos de invocação desse delegado. |
| Equals(Object) |
Determina se o objeto especificado e o delegado atual são do mesmo tipo e compartilham os mesmos destinos, métodos e lista de invocação. |
| GetHashCode() |
Retorna um código hash para o delegado. |
| GetInvocationList() |
Retorna a lista de invocação do delegado. |
| GetMethodImpl() |
Obtém o método representado pelo delegado atual. |
| GetObjectData(SerializationInfo, StreamingContext) |
Obsoleto.
Sem suporte. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| Remove(Delegate, Delegate) |
Remove a última ocorrência da lista de invocação de um delegado da lista de invocação de outro delegado. |
| RemoveAll(Delegate, Delegate) |
Remove todas as ocorrências da lista de invocação de um delegado da lista de invocação de outro delegado. |
| RemoveImpl(Delegate) |
Remove a lista de invocação de um delegado da lista de invocação de outro delegado. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual. (Herdado de Object) |
Operadores
| Nome | Description |
|---|---|
| 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 de Extensão
| Nome | Description |
|---|---|
| GetMethodInfo(Delegate) |
Obtém um objeto que representa o método representado pelo delegado especificado. |