Type.GetEvents Método
Definición
Sobrecargas
GetEvents() |
Devuelve todos los eventos públicos declarados o heredados por el objeto Type actual.Returns all the public events that are declared or inherited by the current Type. |
GetEvents(BindingFlags) |
Cuando se invalida en una clase derivada, busca los eventos declarados o heredados por el objeto Type actual y aplica las restricciones de enlace especificadas.When overridden in a derived class, searches for events that are declared or inherited by the current Type, using the specified binding constraints. |
GetEvents()
public:
virtual cli::array <System::Reflection::EventInfo ^> ^ GetEvents();
public virtual System.Reflection.EventInfo[] GetEvents ();
abstract member GetEvents : unit -> System.Reflection.EventInfo[]
override this.GetEvents : unit -> System.Reflection.EventInfo[]
Public Overridable Function GetEvents () As EventInfo()
Devoluciones
Matriz de objetos EventInfo que representa todos los eventos públicos declarados o heredados por el objeto Type actual.An array of EventInfo objects representing all the public events which are declared or inherited by the current Type.
o bien-or- Matriz vacía de tipo EventInfo si el objeto actual Type no tiene eventos públicos.An empty array of type EventInfo, if the current Type does not have public events.
Implementaciones
Ejemplos
En el ejemplo siguiente se obtiene una matriz de EventInfo objetos, se obtienen todos los eventos de una Button
clase y se muestran los nombres de evento.The following example obtains an array of EventInfo objects, gets all the events for a Button
class, and displays the event names. Para compilar el ejemplo de Visual Basic, utilice la siguiente línea de comandos:To compile the Visual Basic example, use the following command line:
vbc type_getevents1.vb /r:System.Windows.Forms.dll /r:System.dll
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
int main()
{
try
{
Type^ myType = System::Windows::Forms::Button::typeid;
array<EventInfo^>^myEvents = myType->GetEvents();
Console::WriteLine( "The events on the Button class are: " );
for ( int index = 0; index < myEvents->Length; index++ )
{
Console::WriteLine( myEvents[ index ] );
}
}
catch ( SecurityException^ e )
{
Console::WriteLine( "SecurityException: {0}", e->Message );
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "ArgumentNullException: {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
class EventsSample
{
public static void Main()
{
try
{
// Creates a bitmask based on BindingFlags.
BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;
Type myTypeEvent = typeof(System.Windows.Forms.Button);
EventInfo[] myEventsBindingFlags = myTypeEvent.GetEvents(myBindingFlags);
Console.WriteLine("\nThe events on the Button class with the specified BindingFlags are : ");
for (int index = 0; index < myEventsBindingFlags.Length; index++)
{
Console.WriteLine(myEventsBindingFlags[index].ToString());
}
}
catch(SecurityException e)
{
Console.WriteLine("SecurityException :" + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception : " + e.Message);
}
}
}
Imports System.Reflection
Imports System.Security
' Compile this sample using the following command line:
' vbc type_getevents.vb /r:"System.Windows.Forms.dll" /r:"System.dll"
Class EventsSample
Public Shared Sub Main()
Try
' Creates a bitmask based on BindingFlags.
Dim myBindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Public
Dim myTypeEvent As Type = GetType(System.Windows.Forms.Button)
Dim myEventsBindingFlags As EventInfo() = myTypeEvent.GetEvents(myBindingFlags)
Console.WriteLine(ControlChars.Cr + "The events on the Button class with the specified BindingFlags are : ")
Dim index As Integer
For index = 0 To myEventsBindingFlags.Length - 1
Console.WriteLine(myEventsBindingFlags(index).ToString())
Next index
Catch e As SecurityException
Console.WriteLine(("SecurityException :" + e.Message))
Catch e As ArgumentNullException
Console.WriteLine(("ArgumentNullException : " + e.Message))
Catch e As Exception
Console.WriteLine(("Exception : " + e.Message))
End Try
End Sub
End Class
Comentarios
Un evento se considera público para la reflexión si tiene al menos un método o un descriptor de acceso que sea público.An event is considered public to reflection if it has at least one method or accessor that is public. De lo contrario, el evento se considera privado y debe usar BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (en Visual Basic, combinar los valores mediante Or
) para obtenerlo.Otherwise the event is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or
) to get it.
El GetEvents método no devuelve eventos en un orden determinado, como el orden alfabético o de declaración.The GetEvents method does not return events in a particular order, such as alphabetical or declaration order. El código no debe depender del orden en el que se devuelven los eventos, porque el orden varía.Your code must not depend on the order in which events are returned, because that order varies.
Este método se puede invalidar mediante una clase derivada.This method can be overridden by a derived class.
En la tabla siguiente se muestra qué miembros de una clase base son devueltos por los Get
métodos cuando se reflejan en un tipo.The following table shows what members of a base class are returned by the Get
methods when reflecting on a type.
Tipo de miembroMember Type | EstáticoStatic | No estáticaNon-Static |
---|---|---|
ConstructorConstructor | NoNo | NoNo |
CampoField | NoNo | Sí.Yes. Un campo siempre se oculta por nombre y firma.A field is always hide-by-name-and-signature. |
eventoEvent | No es aplicableNot applicable | La regla del sistema de tipos comunes es que la herencia es la misma que la de los métodos que implementan la propiedad.The common type system rule is that the inheritance is the same as that of the methods that implement the property. La reflexión trata las propiedades como ocultas por nombre y firma.Reflection treats properties as hide-by-name-and-signature. Vea la nota 2 a continuación.See note 2 below. |
MétodoMethod | NoNo | Sí.Yes. Un método (tanto virtual como no virtual) se puede ocultar por nombre u ocultar por nombre y por firma.A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature. |
Tipo anidadoNested Type | NoNo | NoNo |
Propiedad.Property | No es aplicableNot applicable | La regla del sistema de tipos comunes es que la herencia es la misma que la de los métodos que implementan la propiedad.The common type system rule is that the inheritance is the same as that of the methods that implement the property. La reflexión trata las propiedades como ocultas por nombre y firma.Reflection treats properties as hide-by-name-and-signature. Vea la nota 2 a continuación.See note 2 below. |
Ocultar por nombre y firma tiene en cuenta todas las partes de la firma, incluidos los modificadores personalizados, los tipos de valor devuelto, los tipos de parámetros, los Sentinel y las convenciones de llamada no administradas.Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. Esta es una comparación binaria.This is a binary comparison.
En la reflexión, las propiedades y los eventos son Hide-by-Name y Signature.For reflection, properties and events are hide-by-name-and-signature. Si tiene una propiedad con un descriptor de acceso get y set en la clase base, pero la clase derivada solo tiene un descriptor de acceso get, la propiedad de la clase derivada oculta la propiedad de clase base y no podrá tener acceso al establecedor en la clase base.If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.
Los atributos personalizados no forman parte del sistema de tipos comunes.Custom attributes are not part of the common type system.
Si el objeto actual Type representa un tipo genérico construido, este método devuelve los EventInfo objetos con los parámetros de tipo reemplazados por los argumentos de tipo adecuados.If the current Type represents a constructed generic type, this method returns the EventInfo objects with the type parameters replaced by the appropriate type arguments.
Si el actual Type representa un parámetro de tipo en la definición de un tipo genérico o de un método genérico, este método busca los eventos de la restricción de clase.If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the events of the class constraint.
Consulte también
Se aplica a
GetEvents(BindingFlags)
Cuando se invalida en una clase derivada, busca los eventos declarados o heredados por el objeto Type actual y aplica las restricciones de enlace especificadas.When overridden in a derived class, searches for events that are declared or inherited by the current Type, using the specified binding constraints.
public:
abstract cli::array <System::Reflection::EventInfo ^> ^ GetEvents(System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.EventInfo[] GetEvents (System.Reflection.BindingFlags bindingAttr);
abstract member GetEvents : System.Reflection.BindingFlags -> System.Reflection.EventInfo[]
Public MustOverride Function GetEvents (bindingAttr As BindingFlags) As EventInfo()
Parámetros
- bindingAttr
- BindingFlags
Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.A bitwise combination of the enumeration values that specify how the search is conducted.
o bien-or-
Default para que se devuelva una matriz vacía.Default to return an empty array.
Devoluciones
Matriz de objetos EventInfo que representa todos los eventos declarados o heredados por el objeto Type actual que cumplen las restricciones de enlace especificadas.An array of EventInfo objects representing all events that are declared or inherited by the current Type that match the specified binding constraints.
o bien-or- Matriz vacía de tipo EventInfo si el objeto Type actual no tiene eventos o si ninguno de los eventos coincide con las restricciones de enlace.An empty array of type EventInfo, if the current Type does not have events, or if none of the events match the binding constraints.
Implementaciones
Ejemplos
En el ejemplo siguiente se obtiene una matriz de EventInfo objetos que coinciden con las marcas de enlace especificadas, se obtienen todos los eventos de una Button
clase y se muestran los nombres de evento.The following example obtains an array of EventInfo objects that match the specified binding flags, gets all the events for a Button
class, and displays the event names. Para compilar el ejemplo de Visual Basic, utilice la siguiente línea de comandos:To compile the Visual Basic example, use the following command line:
vbc type_getevents2.vb /r:System.Windows.Forms.dll /r:System.dll
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
int main()
{
try
{
// Create a bitmask based on BindingFlags.
BindingFlags myBindingFlags = static_cast<BindingFlags>(BindingFlags::Instance | BindingFlags::Public);
Type^ myTypeEvent = System::Windows::Forms::Button::typeid;
array<EventInfo^>^myEventsBindingFlags = myTypeEvent->GetEvents( myBindingFlags );
Console::WriteLine( "\nThe events on the Button class with the specified BindingFlags are:" );
for ( int index = 0; index < myEventsBindingFlags->Length; index++ )
{
Console::WriteLine( myEventsBindingFlags[ index ] );
}
}
catch ( SecurityException^ e )
{
Console::WriteLine( "SecurityException: {0}", e->Message );
}
catch ( ArgumentNullException^ e )
{
Console::WriteLine( "ArgumentNullException: {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception: {0}", e->Message );
}
}
using System;
using System.Reflection;
using System.Security;
class EventsSample
{
public static void Main()
{
try
{
// Create a bitmask based on BindingFlags.
BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;
Type myTypeEvent = typeof(System.Windows.Forms.Button);
EventInfo[] myEventsBindingFlags = myTypeEvent.GetEvents(myBindingFlags);
Console.WriteLine("\nThe events on the Button class with the specified BindingFlags are:");
for (int index = 0; index < myEventsBindingFlags.Length; index++)
{
Console.WriteLine(myEventsBindingFlags[index].ToString());
}
}
catch(SecurityException e)
{
Console.WriteLine("SecurityException:" + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
}
Imports System.Reflection
Imports System.Security
Imports System.Windows.Forms
Class EventsSample
Public Shared Sub Main()
Try
' Create a bitmask based on BindingFlags.
Dim myBindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Public
Dim myTypeEvent As Type = GetType(System.Windows.Forms.Button)
Dim myEventsBindingFlags As EventInfo() = myTypeEvent.GetEvents(myBindingFlags)
Console.WriteLine(ControlChars.Cr + "The events on the Button class with the specified BindingFlags are:")
Dim index As Integer
For index = 0 To myEventsBindingFlags.Length - 1
Console.WriteLine(myEventsBindingFlags(index).ToString())
Next index
Catch e As SecurityException
Console.WriteLine("SecurityException:" + e.Message)
Catch e As ArgumentNullException
Console.WriteLine("ArgumentNullException: " + e.Message)
Catch e As Exception
Console.WriteLine("Exception: " + e.Message)
End Try
End Sub
End Class
Comentarios
El GetEvents método no devuelve eventos en un orden determinado, como el orden alfabético o de declaración.The GetEvents method does not return events in a particular order, such as alphabetical or declaration order. El código no debe depender del orden en el que se devuelven los eventos, porque el orden varía.Your code must not depend on the order in which events are returned, because that order varies.
BindingFlagsSe pueden usar las siguientes marcas de filtro para definir qué eventos se van a incluir en la búsqueda:The following BindingFlags filter flags can be used to define which events to include in the search:
Debe especificar
BindingFlags.Instance
oBindingFlags.Static
para obtener un valor devuelto.You must specify eitherBindingFlags.Instance
orBindingFlags.Static
in order to get a return.Especifique
BindingFlags.Public
que se incluyan eventos públicos en la búsqueda.SpecifyBindingFlags.Public
to include public events in the search.Especifique
BindingFlags.NonPublic
que se incluyan eventos no públicos (es decir, eventos privados, internos y protegidos) en la búsqueda.SpecifyBindingFlags.NonPublic
to include non-public events (that is, private, internal, and protected events) in the search. Solo se devuelven los eventos protegidos e internos de las clases base; no se devuelven eventos privados en clases base.Only protected and internal events on base classes are returned; private events on base classes are not returned.Especifique
BindingFlags.FlattenHierarchy
para incluirpublic
yprotected
miembros estáticos en la jerarquía;private
los miembros estáticos de las clases heredadas no se incluyen.SpecifyBindingFlags.FlattenHierarchy
to includepublic
andprotected
static members up the hierarchy;private
static members in inherited classes are not included.
BindingFlagsSe pueden usar las siguientes marcas de modificador para cambiar el funcionamiento de la búsqueda:The following BindingFlags modifier flags can be used to change how the search works:
BindingFlags.DeclaredOnly
para buscar solo los eventos declarados en Type , no los eventos que se han heredado simplemente.BindingFlags.DeclaredOnly
to search only the events declared on the Type, not events that were simply inherited.
Vea System.Reflection.BindingFlags para obtener más información.See System.Reflection.BindingFlags for more information.
Un evento se considera público para la reflexión si tiene al menos un método o un descriptor de acceso que sea público.An event is considered public to reflection if it has at least one method or accessor that is public. De lo contrario, el evento se considera privado y debe usar BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (en Visual Basic, combinar los valores mediante Or
) para obtenerlo.Otherwise the event is considered private, and you must use BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (in Visual Basic, combine the values using Or
) to get it.
Si el objeto actual Type representa un tipo genérico construido, este método devuelve los EventInfo objetos con los parámetros de tipo reemplazados por los argumentos de tipo adecuados.If the current Type represents a constructed generic type, this method returns the EventInfo objects with the type parameters replaced by the appropriate type arguments.
Si el actual Type representa un parámetro de tipo en la definición de un tipo genérico o de un método genérico, este método busca los eventos de la restricción de clase.If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the events of the class constraint.