Type.GetEvent Método

Definición

Obtiene un evento específico declarado o heredado por el objeto Type actual.Gets a specific event declared or inherited by the current Type.

Sobrecargas

GetEvent(String)

Devuelve el objeto EventInfo que representa el evento público especificado.Returns the EventInfo object representing the specified public event.

GetEvent(String, BindingFlags)

Cuando se invalida en una clase derivada, devuelve el objeto EventInfo que representa el evento especificado y aplica las restricciones de enlace especificadas.When overridden in a derived class, returns the EventInfo object representing the specified event, using the specified binding constraints.

GetEvent(String)

Devuelve el objeto EventInfo que representa el evento público especificado.Returns the EventInfo object representing the specified public event.

public:
 virtual System::Reflection::EventInfo ^ GetEvent(System::String ^ name);
public System.Reflection.EventInfo GetEvent (string name);
abstract member GetEvent : string -> System.Reflection.EventInfo
override this.GetEvent : string -> System.Reflection.EventInfo
Public Function GetEvent (name As String) As EventInfo

Parámetros

name
String

Cadena que contiene el nombre de un evento que la clase Type actual declaró o heredó.The string containing the name of an event that is declared or inherited by the current Type.

Devoluciones

Objeto que representa el evento público especificado que declara o hereda el Type actual, si se encuentra; de lo contrario es null.The object representing the specified public event that is declared or inherited by the current Type, if found; otherwise, null.

Implementaciones

Excepciones

name es null.name is null.

Ejemplos

En el ejemplo siguiente se crea un objeto de EventInfo y se obtiene el evento para una clase de botón para el evento especificado.The following example creates an EventInfo object and gets the event for a button class for the specified event.

#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;
      EventInfo^ myEvent = myType->GetEvent( "Click" );
      if ( myEvent != nullptr )
      {
         Console::WriteLine( "Looking for the Click event in the Button class." );
         Console::WriteLine( myEvent );
      }
      else
            Console::WriteLine( "The Click event is not available in 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
        {

            Type myType = typeof(System.Windows.Forms.Button);
            EventInfo myEvent = myType.GetEvent("Click");
            if(myEvent != null)
            {
                Console.WriteLine("Looking for the Click event in the Button class.");
                Console.WriteLine(myEvent.ToString());
            }
            else
                Console.WriteLine("The Click event is not available in 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
            Dim myType As Type = GetType(System.Windows.Forms.Button)
            Dim myEvent As EventInfo = myType.GetEvent("Click")
            If Not (myEvent Is Nothing) Then
                Console.WriteLine(ControlChars.Cr + "Looking for the Click event in the Button class.")
                Console.WriteLine(ControlChars.Cr + myEvent.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

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 con 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.

La búsqueda de name distingue entre mayúsculas y minúsculas.The search for name is case-sensitive. La búsqueda incluye eventos públicos estáticos y de instancia pública.The search includes public static and public instance events.

En la tabla siguiente se muestra qué miembros de una clase base son devueltos por los métodos Get al reflejar 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.
  1. 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.

  2. 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.

  3. Los atributos personalizados no forman parte del sistema de tipos comunes.Custom attributes are not part of the common type system.

Si el Type actual representa un tipo genérico construido, este método devuelve el EventInfo 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 with the type parameters replaced by the appropriate type arguments.

Si el Type actual 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:

GetEvent(String, BindingFlags)

Cuando se invalida en una clase derivada, devuelve el objeto EventInfo que representa el evento especificado y aplica las restricciones de enlace especificadas.When overridden in a derived class, returns the EventInfo object representing the specified event, using the specified binding constraints.

public:
 abstract System::Reflection::EventInfo ^ GetEvent(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.EventInfo GetEvent (string name, System.Reflection.BindingFlags bindingAttr);
abstract member GetEvent : string * System.Reflection.BindingFlags -> System.Reflection.EventInfo
Public MustOverride Function GetEvent (name As String, bindingAttr As BindingFlags) As EventInfo

Parámetros

name
String

Cadena que contiene el nombre de un evento que la clase Type actual declara o hereda.The string containing the name of an event which is declared or inherited by the current Type.

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 devolver null.Default to return null.

Devoluciones

Objeto que representa el evento especificado que declara o hereda el Type actual, si se encuentra; de lo contrario, es null.The object representing the specified event that is declared or inherited by the current Type, if found; otherwise, null.

Implementaciones

Excepciones

name es null.name is null.

Ejemplos

En el ejemplo de código siguiente se usa el método GetEvent(String, BindingFlags) para buscar en un tipo un evento público o no público denominado "click" que no se static (Shared en Visual Basic).The following code example uses the GetEvent(String, BindingFlags) method to search a type for a public or non-public event named "Click" that is not static (Shared in Visual Basic).

#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

Comentarios

Se pueden usar las siguientes marcas de filtro de BindingFlags para definir qué eventos se deben 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 o BindingFlags.Static para obtener un valor devuelto.You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • Especifique BindingFlags.Public para incluir eventos públicos en la búsqueda.Specify BindingFlags.Public to include public events in the search.

  • Especifique BindingFlags.NonPublic para incluir eventos no públicos (es decir, eventos privados, internos y protegidos) en la búsqueda.Specify BindingFlags.NonPublic to include non-public events (that is, private, internal, and protected events) in the search.

  • Especifique BindingFlags.FlattenHierarchy para incluir public y protected miembros estáticos en la jerarquía. no se incluyen private miembros estáticos de las clases heredadas.Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

Se pueden usar las siguientes marcas de modificador de BindingFlags para cambiar el funcionamiento de la búsqueda:The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase para omitir las mayúsculas y minúsculas de name.BindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly para buscar solo los eventos declarados en el Type, no los eventos que simplemente se heredaron.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 con 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 Type actual representa un tipo genérico construido, este método devuelve el EventInfo 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 with the type parameters replaced by the appropriate type arguments.

Si el Type actual 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