EventInfo Classe
Definição
Descobre os atributos de um evento e fornece acesso aos metadados de evento.Discovers the attributes of an event and provides access to event metadata.
public ref class EventInfo abstract : System::Reflection::MemberInfo, System::Runtime::InteropServices::_EventInfo
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class EventInfo : System.Reflection.MemberInfo, System.Runtime.InteropServices._EventInfo
type EventInfo = class
inherit MemberInfo
interface _EventInfo
Public MustInherit Class EventInfo
Inherits MemberInfo
Implements _EventInfo
- Herança
- Derivado
- Atributos
- Implementações
Exemplos
O código a seguir obtém EventInfo um objeto para Click o evento da Button classe.The following code gets an EventInfo object for the Click event of the Button class.
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
using namespace System::Windows::Forms;
int main()
{
try
{
// Creates a bitmask based on BindingFlags.
BindingFlags myBindingFlags = static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public | BindingFlags::NonPublic);
Type^ myTypeBindingFlags = System::Windows::Forms::Button::typeid;
EventInfo^ myEventBindingFlags = myTypeBindingFlags->GetEvent( "Click", myBindingFlags );
if ( myEventBindingFlags != nullptr )
{
Console::WriteLine( "Looking for the Click event in the Button class with the specified BindingFlags." );
Console::WriteLine( myEventBindingFlags );
}
else
Console::WriteLine( "The Click event is not available with the Button class." );
}
catch ( SecurityException^ e )
{
Console::WriteLine( "An exception occurred." );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "An exception occurred." );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "The following exception was raised : {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
class MyEventExample
{
public static void Main()
{
try
{
// Creates a bitmask based on BindingFlags.
BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Type myTypeBindingFlags = typeof(System.Windows.Forms.Button);
EventInfo myEventBindingFlags = myTypeBindingFlags.GetEvent("Click", myBindingFlags);
if(myEventBindingFlags != null)
{
Console.WriteLine("Looking for the Click event in the Button class with the specified BindingFlags.");
Console.WriteLine(myEventBindingFlags.ToString());
}
else
Console.WriteLine("The Click event is not available with the Button class.");
}
catch(SecurityException e)
{
Console.WriteLine("An exception occurred.");
Console.WriteLine("Message :"+e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("An exception occurred.");
Console.WriteLine("Message :"+e.Message);
}
catch(Exception e)
{
Console.WriteLine("The following exception was raised : {0}",e.Message);
}
}
}
Imports System.Reflection
Imports System.Security
' Compile this sample using the following command line:
' vbc type_getevent.vb /r:"System.Windows.Forms.dll" /r:"System.dll"
Class MyEventExample
Public Shared Sub Main()
Try
' Creates a bitmask comprising BindingFlags.
Dim myBindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Public _
Or BindingFlags.NonPublic
Dim myTypeBindingFlags As Type = GetType(System.Windows.Forms.Button)
Dim myEventBindingFlags As EventInfo = myTypeBindingFlags.GetEvent("Click", myBindingFlags)
If myEventBindingFlags IsNot Nothing Then
Console.WriteLine("Looking for the Click event in the Button class with the specified BindingFlags.")
Console.WriteLine(myEventBindingFlags.ToString())
Else
Console.WriteLine("The Click event is not available with the Button class.")
End If
Catch e As SecurityException
Console.WriteLine("An exception occurred.")
Console.WriteLine("Message :" + e.Message)
Catch e As ArgumentNullException
Console.WriteLine("An exception occurred.")
Console.WriteLine("Message :" + e.Message)
Catch e As Exception
Console.WriteLine("The following exception was raised : {0}", e.Message)
End Try
End Sub
End Class
Comentários
Use a EventInfo classe para inspecionar eventos e conectar manipuladores de eventos, conforme mostrado no código de exemplo para o AddEventHandler método.Use the EventInfo class to inspect events and to hook up event handlers, as shown in the example code for the AddEventHandler method.
Observação
EventInfoNão se destina a ser usado para gerar eventos.EventInfo is not intended to be used to raise events. Um objeto gera eventos conforme determinado pelo seu estado interno.An object raises events as dictated by its internal state.
Os eventos são usados com delegados.Events are used with delegates. Um ouvinte de eventos cria uma instância de um delegado de manipulador de eventos que é invocado sempre que o evento é gerado por uma origem de evento.An event listener instantiates an event-handler delegate that is invoked whenever the event is raised by an event source. Para se conectar à origem do evento, o ouvinte de eventos adiciona esse delegado à lista de invocação na origem.In order to connect to the event source, the event listener adds this delegate to the invocation list on the source. Quando o evento é gerado, o método Invoke do delegado do manipulador de eventos é chamado.When the event is raised, the invoke method of the event-handler delegate is called. Há suporte para notificações de eventos multicast e de conversão única.Both multicast and single-cast event notifications are supported. Os Add
métodos Remove
e, bem como a classe delegada do manipulador de eventos associada a um evento, devem ser marcados nos metadados.The Add
and Remove
methods, as well as the event-handler delegate class associated with an event, must be marked in the metadata.
Delegados são ponteiros de função orientados a objeto.Delegates are object-oriented function pointers. Em C ou C++, um ponteiro de função é uma referência a um método.In C or C++, a function pointer is a reference to a method. Ao contrário do ponteiro do C C++ ou da função, um delegado contém duas referências: uma referência a um método e uma referência a um objeto que dá suporte ao método.In contrast to the C or C++ function pointer, a delegate contains two references: a reference to a method and a reference to an object that supports the method. Os delegados podem invocar um método sem saber o tipo de classe que declara ou herda o método.Delegates can invoke a method without knowing the class type that declares or inherits the method. Os delegados só precisam saber o tipo de retorno e a lista de parâmetros do método.Delegates need only know the return type and parameter list of the method.
O modelo de evento funciona igualmente bem para delegados de multicast e de difusão única.The event model works equally well for single-cast and multicast delegates. Quando o método Invoke do delegado é chamado, apenas um único objeto terá um método chamado nele.When the delegate's invoke method is called, only a single object will have a method called on it. Um modificador multicast pode ser aplicado a uma declaração delegate, que permite que vários métodos sejam chamados quando o método Invoke do delegado é chamado.A multicast modifier can be applied to a delegate declaration, which allows multiple methods to be called when the invoke method of the delegate is called.
Chamar ICustomAttributeProvider.GetCustomAttributes on EventInfo
quando o inherit
parâmetro de GetCustomAttributes
é nãopercorreahierarquiadetipos.true
Calling ICustomAttributeProvider.GetCustomAttributes on EventInfo
when the inherit
parameter of GetCustomAttributes
is true
does not walk the type hierarchy. Use System.Attribute para herdar atributos personalizados.Use System.Attribute to inherit custom attributes.
Notas aos Implementadores
Ao herdar do EventInfo
, você deve substituir os seguintes membros: GetAddMethod(Boolean), GetRemoveMethod(Boolean)e GetRaiseMethod(Boolean).When you inherit from EventInfo
, you must override the following members: GetAddMethod(Boolean), GetRemoveMethod(Boolean), and GetRaiseMethod(Boolean).
Construtores
EventInfo() |
Inicializa uma nova instância da classe |
Propriedades
AddMethod |
Obtém o objeto MethodInfo para o método AddEventHandler(Object, Delegate) do evento, incluindo métodos não públicos.Gets the MethodInfo object for the AddEventHandler(Object, Delegate) method of the event, including non-public methods. |
Attributes |
Obtém os atributos desse evento.Gets the attributes for this event. |
CustomAttributes |
Obtém uma coleção que contém os atributos personalizados desse membro.Gets a collection that contains this member's custom attributes. (Herdado de MemberInfo) |
DeclaringType |
Obtém a classe que declara esse membro.Gets the class that declares this member. (Herdado de MemberInfo) |
EventHandlerType |
Obtém o objeto |
IsCollectible |
Obtém um valor que indica se este objeto MemberInfo faz parte de um assembly mantido em uma coleção AssemblyLoadContext.Gets a value that indicates whether this MemberInfo object is part of an assembly held in a collectible AssemblyLoadContext. (Herdado de MemberInfo) |
IsMulticast |
Obtém um valor que indica se o evento é multicast.Gets a value indicating whether the event is multicast. |
IsSpecialName |
Obtém um valor que indica se o |
MemberType |
Obtém um valor MemberTypes que indica que esse membro é um evento.Gets a MemberTypes value indicating that this member is an event. |
MetadataToken |
Obtém um valor que identifica um elemento de metadados.Gets a value that identifies a metadata element. (Herdado de MemberInfo) |
Module |
Obtém o módulo no qual o tipo que declara o membro representado pelo MemberInfo atual está definido.Gets the module in which the type that declares the member represented by the current MemberInfo is defined. (Herdado de MemberInfo) |
Name |
Obtém o nome do membro atual.Gets the name of the current member. (Herdado de MemberInfo) |
RaiseMethod |
Obtém o método que é chamado quando o evento é acionado, incluindo métodos não públicos.Gets the method that is called when the event is raised, including non-public methods. |
ReflectedType |
Obtém o objeto de classe que foi usado para obter esta instância de |
RemoveMethod |
Obtém o objeto |
Métodos
AddEventHandler(Object, Delegate) |
Adiciona um manipulador de eventos à origem de um evento.Adds an event handler to an event source. |
Equals(Object) |
Retorna um valor que indica se essa instância é igual a um objeto especificado.Returns a value that indicates whether this instance is equal to a specified object. |
GetAddMethod() |
Retorna o método usado para adicionar um delegado de manipulador de eventos para a origem do evento.Returns the method used to add an event handler delegate to the event source. |
GetAddMethod(Boolean) |
Quando substituído em uma classe derivada, recupera o objeto |
GetCustomAttributes(Boolean) |
Quando substituído em uma classe derivada, retorna uma matriz de todos os atributos personalizados aplicados a esse membro.When overridden in a derived class, returns an array of all custom attributes applied to this member. (Herdado de MemberInfo) |
GetCustomAttributes(Type, Boolean) |
Quando substituído em uma classe derivada, retorna uma matriz de atributos personalizados aplicados a esse membro e identificados por Type.When overridden in a derived class, returns an array of custom attributes applied to this member and identified by Type. (Herdado de MemberInfo) |
GetCustomAttributesData() |
Retorna uma lista de objetos CustomAttributeData que representam dados sobre os atributos que foram aplicados ao membro de destino.Returns a list of CustomAttributeData objects representing data about the attributes that have been applied to the target member. (Herdado de MemberInfo) |
GetHashCode() |
Retorna o código hash para essa instância.Returns the hash code for this instance. |
GetOtherMethods() |
Retorna os métodos públicos que foram associados um evento em metadados usando a diretiva |
GetOtherMethods(Boolean) |
Retorna os métodos que foram associados ao evento nos metadados usando a diretiva |
GetRaiseMethod() |
Retorna o método que é chamado quando o evento é acionado.Returns the method that is called when the event is raised. |
GetRaiseMethod(Boolean) |
Quando substituído em uma classe derivada, recupera o método chamado quando o evento é acionado, especificando se métodos não públicos devem ou não ser retornados.When overridden in a derived class, returns the method that is called when the event is raised, specifying whether to return non-public methods. |
GetRemoveMethod() |
Retorna o método usado para remover um delegado de manipulador de eventos da origem do evento.Returns the method used to remove an event handler delegate from the event source. |
GetRemoveMethod(Boolean) |
Quando substituído em uma classe derivada, recupera o objeto |
GetType() | |
HasSameMetadataDefinitionAs(MemberInfo) | (Herdado de MemberInfo) |
IsDefined(Type, Boolean) |
Quando substituído em uma classe derivada, indica se um ou mais atributos do tipo especificado ou de seus tipos derivados são aplicados a esse membro.When overridden in a derived class, indicates whether one or more attributes of the specified type or of its derived types is applied to this member. (Herdado de MemberInfo) |
MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
RemoveEventHandler(Object, Delegate) |
Remove um manipulador de eventos de uma origem de evento.Removes an event handler from an event source. |
ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Operadores
Equality(EventInfo, EventInfo) |
Indica se dois objetos EventInfo são iguais.Indicates whether two EventInfo objects are equal. |
Inequality(EventInfo, EventInfo) |
Indica se dois objetos EventInfo não são iguais.Indicates whether two EventInfo objects are not equal. |
Implantações explícitas de interface
_EventInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers. |
_EventInfo.GetType() |
Retorna um objeto |
_EventInfo.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera as informações do tipo de um objeto, que podem ser usadas para obter informações de tipo para uma interface.Retrieves the type information for an object, which can then be used to get the type information for an interface. |
_EventInfo.GetTypeInfoCount(UInt32) |
Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). |
_EventInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object. |
_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers. (Herdado de MemberInfo) |
_MemberInfo.GetType() |
Obtém um objeto Type que representa a classe MemberInfo.Gets a Type object representing the MemberInfo class. (Herdado de MemberInfo) |
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera as informações do tipo de um objeto, que podem ser usadas para obter informações de tipo para uma interface.Retrieves the type information for an object, which can then be used to get the type information for an interface. (Herdado de MemberInfo) |
_MemberInfo.GetTypeInfoCount(UInt32) |
Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Herdado de MemberInfo) |
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object. (Herdado de MemberInfo) |
ICustomAttributeProvider.GetCustomAttributes(Boolean) | (Herdado de MemberInfo) |
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) | (Herdado de MemberInfo) |
ICustomAttributeProvider.IsDefined(Type, Boolean) | (Herdado de MemberInfo) |
Métodos de Extensão
GetCustomAttribute(MemberInfo, Type) |
Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado.Retrieves a custom attribute of a specified type that is applied to a specified member. |
GetCustomAttribute(MemberInfo, Type, Boolean) |
Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member. |
GetCustomAttribute<T>(MemberInfo) |
Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado.Retrieves a custom attribute of a specified type that is applied to a specified member. |
GetCustomAttribute<T>(MemberInfo, Boolean) |
Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member. |
GetCustomAttributes(MemberInfo) |
Recupera uma coleção de atributos personalizados que são aplicados a um membro especificado.Retrieves a collection of custom attributes that are applied to a specified member. |
GetCustomAttributes(MemberInfo, Boolean) |
Recupera uma coleção de atributos personalizados aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.Retrieves a collection of custom attributes that are applied to a specified member, and optionally inspects the ancestors of that member. |
GetCustomAttributes(MemberInfo, Type) |
Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado.Retrieves a collection of custom attributes of a specified type that are applied to a specified member. |
GetCustomAttributes(MemberInfo, Type, Boolean) |
Recupera uma coleção de atributos personalizados de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member. |
GetCustomAttributes<T>(MemberInfo) |
Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado.Retrieves a collection of custom attributes of a specified type that are applied to a specified member. |
GetCustomAttributes<T>(MemberInfo, Boolean) |
Recupera uma coleção de atributos personalizados de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member. |
IsDefined(MemberInfo, Type) |
Indica se os atributos personalizados de um tipo especificados são aplicados a um membro especificado.Indicates whether custom attributes of a specified type are applied to a specified member. |
IsDefined(MemberInfo, Type, Boolean) |
Indica se os atributos personalizados de um tipo especificado são aplicados a um membro especificado e, opcionalmente, aplicados a seus ancestrais.Indicates whether custom attributes of a specified type are applied to a specified member, and, optionally, applied to its ancestors. |
GetAddMethod(EventInfo) | |
GetAddMethod(EventInfo, Boolean) | |
GetRaiseMethod(EventInfo) | |
GetRaiseMethod(EventInfo, Boolean) | |
GetRemoveMethod(EventInfo) | |
GetRemoveMethod(EventInfo, Boolean) | |
GetMetadataToken(MemberInfo) |
Obtém um token de metadados para o membro fornecido, se disponível.Gets a metadata token for the given member, if available. |
HasMetadataToken(MemberInfo) |
Retorna um valor que indica se um token de metadados está disponível para o membro especificado.Returns a value that indicates whether a metadata token is available for the specified member. |
Segurança
InheritanceDemand
para confiança total de herdeiros.for full trust for inheritors. Esta classe não pode ser herdada pelo código parcialmente confiável.This class cannot be inherited by partially trusted code.
Aplica-se a
Acesso thread-safe
Este tipo é thread-safe.This type is thread safe.