Type.GetProperty Método

Definición

Obtiene una propiedad específica del objeto Type actual.

Sobrecargas

GetProperty(String, Type, Type[])

Busca la propiedad pública especificada cuyos parámetros coincidan con los tipos de argumentos especificados.

GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

Busca la propiedad especificada cuyos parámetros coincidan con los tipos y modificadores de argumentos especificados, mediante las restricciones de enlace indicadas.

GetProperty(String, Type, Type[], ParameterModifier[])

Busca la propiedad pública especificada cuyos parámetros coincidan con los tipos y modificadores de los argumentos especificados.

GetProperty(String, Type[])

Busca la propiedad pública especificada cuyos parámetros coincidan con los tipos de argumentos especificados.

GetProperty(String, Type)

Busca la propiedad pública con el nombre especificado y el tipo de valor devuelto.

GetProperty(String, BindingFlags)

Busca la propiedad especificada, mediante las restricciones de enlace especificadas.

GetProperty(String)

Busca la propiedad pública con el nombre especificado.

GetProperty(String, Type, Type[])

Busca la propiedad pública especificada cuyos parámetros coincidan con los tipos de argumentos especificados.

public:
 System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types);
public:
 virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types);
public System.Reflection.PropertyInfo? GetProperty (string name, Type? returnType, Type[] types);
public System.Reflection.PropertyInfo GetProperty (string name, Type returnType, Type[] types);
member this.GetProperty : string * Type * Type[] -> System.Reflection.PropertyInfo
abstract member GetProperty : string * Type * Type[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type * Type[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, returnType As Type, types As Type()) As PropertyInfo

Parámetros

name
String

Cadena que contiene el nombre de la propiedad pública que se va a obtener.

returnType
Type

Tipo de valor devuelto de la propiedad.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que la propiedad indizada debe obtener.

O bien

Matriz vacía del tipo Type (es decir, Type[] types = new Type[0]) para obtener una propiedad que no esté indizada.

Devoluciones

PropertyInfo

Objeto que representa la propiedad pública cuyos parámetros coinciden con los tipos de argumentos especificados, si se encuentra; en caso contrario, null.

Implementaciones

Excepciones

Se encontró más de una propiedad con el nombre especificado y que coincide con los tipos de argumento especificados.

name es null.

O bien

types es null.

types es multidimensional.

Un elemento de types es null.

Comentarios

Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso público. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (en Visual Basic, combinar los valores mediante Or) para obtenerla.

La búsqueda distingue name mayúsculas de minúsculas. La búsqueda incluye propiedades de instancia pública estática y pública.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con PropertyInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en las propiedades de la restricción de clase.

Indizadores y propiedades predeterminadas

Visual Basic 2005, Visual C# 2005 y Visual C++ 2005 tienen una sintaxis simplificada para acceder a las propiedades indizada y permiten que una propiedad indexada sea un valor predeterminado para su tipo. Por ejemplo, si la variable myList hace referencia a ArrayList, la sintaxis myList[3] (myList(3) en Visual Basic) recupera el elemento con el índice de 3. Puede sobrecargar la propiedad .

En C#, esta característica se denomina indexador y no se puede hacer referencia por nombre. De forma predeterminada, un indexador de C# aparece en los metadatos como una propiedad indizada denominada "Item". Sin embargo, un desarrollador de biblioteca de clases puede usar el IndexerNameAttribute atributo para cambiar el nombre del indexador en los metadatos. Por ejemplo, la String clase tiene un indexador denominado Chars[]. Las propiedades indizada creadas mediante lenguajes distintos de C# también pueden tener nombres distintos de Item.

Para determinar si un tipo tiene una propiedad predeterminada, use el GetCustomAttributes(Type, Boolean) método para probar el DefaultMemberAttribute atributo. Si el tipo tiene DefaultMemberAttribute, la MemberName propiedad devuelve el nombre de la propiedad predeterminada.

Consulte también

Se aplica a

GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

Busca la propiedad especificada cuyos parámetros coincidan con los tipos y modificadores de argumentos especificados, mediante las restricciones de enlace indicadas.

public:
 virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, Type ^ returnType, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.PropertyInfo? GetProperty (string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type? returnType, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.PropertyInfo GetProperty (string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers);
abstract member GetProperty : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * System.Reflection.BindingFlags * System.Reflection.Binder * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, bindingAttr As BindingFlags, binder As Binder, returnType As Type, types As Type(), modifiers As ParameterModifier()) As PropertyInfo

Parámetros

name
String

Cadena que contiene el nombre de la propiedad que se va a obtener.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

O bien

Default para devolver null.

binder
Binder

Objeto que define un conjunto de propiedades y permite realizar operaciones de enlace, que pueden incluir la selección de un método sobrecargado, la coerción de tipos de argumentos y la invocación de un miembro mediante reflexión.

O bien

Referencia nula (Nothing en Visual Basic) para usar la propiedad DefaultBinder.

returnType
Type

Tipo de valor devuelto de la propiedad.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que la propiedad indizada debe obtener.

O bien

Matriz vacía del tipo Type (es decir, Type[] types = new Type[0]) para obtener una propiedad que no esté indizada.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. El enlazador predeterminado no procesa este parámetro.

Devoluciones

PropertyInfo

Objeto que representa la propiedad que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Se encontró más de una propiedad con el nombre especificado y que coincide con las restricciones de enlace especificadas.

name es null.

O bien

types es null.

types es multidimensional.

O bien

modifiers es multidimensional.

O bien

types y modifiers no tienen la misma longitud.

Un elemento de types es null.

Comentarios

Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso público. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (en Visual Basic, combinar los valores mediante Or) para obtenerla.

Aunque el enlazador predeterminado no procesa ParameterModifier (el modifiers parámetro ), puede usar la clase abstracta System.Reflection.Binder para escribir un enlazador personalizado que procese modifiers. ParameterModifier solo se usa al llamar a través de la interoperabilidad COM y solo se controlan los parámetros que se pasan por referencia.

En la tabla siguiente se muestra qué miembros de una clase base devuelven los Get métodos al reflejar en un tipo.

Tipo de miembro Estático No estático
Constructor No No
Campo No Sí. Un campo siempre está ocultado por nombre y firma.
evento No es aplicable La regla del sistema de tipos común es que la herencia es la misma que la de los métodos que implementan la propiedad . La reflexión trata las propiedades como hide-by-name-and-signature. Consulte la nota 2 a continuación.
Método No Sí. Un método (tanto virtual como no virtual) puede ocultarse por nombre u ocultar por nombre y firma.
Tipo anidado No No
Propiedad. No es aplicable La regla del sistema de tipos común es que la herencia es la misma que la de los métodos que implementan la propiedad . La reflexión trata las propiedades como hide-by-name-and-signature. Consulte la nota 2 a continuación.
  1. Hide-by-name-and-signature tiene en cuenta todas las partes de la firma, incluidos modificadores personalizados, tipos de valor devuelto, tipos de parámetros, sentinels y convenciones de llamada no administradas. Se trata de una comparación binaria.

  2. En el caso de la reflexión, las propiedades y los eventos son hide-by-name-and-signature. Si tiene una propiedad con un descriptor de acceso get y un set en la clase base, pero la clase derivada solo tiene un descriptor de acceso get, la propiedad de clase derivada oculta la propiedad de clase base y no podrá acceder al establecedor en la clase base.

  3. Los atributos personalizados no forman parte del sistema de tipos común.

Las marcas de filtro siguientes BindingFlags se pueden usar para definir qué propiedades se van a incluir en la búsqueda:

  • Debe especificar o BindingFlags.InstanceBindingFlags.Static para obtener una devolución.

  • Especifique BindingFlags.Public para incluir propiedades públicas en la búsqueda.

  • Especifique BindingFlags.NonPublic que incluya propiedades no públicas (es decir, propiedades privadas, internas y protegidas) en la búsqueda.

  • Especifique BindingFlags.FlattenHierarchy para incluir y protected miembros public estáticos en la jerarquía; private no se incluyen los miembros estáticos de las clases heredadas.

Se pueden usar las marcas modificadores siguientes BindingFlags para cambiar el funcionamiento de la búsqueda:

  • BindingFlags.IgnoreCase para pasar por alto el caso de name.

  • BindingFlags.DeclaredOnly para buscar solo las propiedades declaradas en , Typeno las propiedades que simplemente se heredaron.

Vea System.Reflection.BindingFlags para obtener más información.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con PropertyInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en las propiedades de la restricción de clase.

Indizadores y propiedades predeterminadas

Visual Basic 2005, Visual C# 2005 y Visual C++ 2005 tienen una sintaxis simplificada para acceder a las propiedades indizada y permiten que una propiedad indexada sea un valor predeterminado para su tipo. Por ejemplo, si la variable myList hace referencia a ArrayList, la sintaxis myList[3] (myList(3) en Visual Basic) recupera el elemento con el índice de 3. Puede sobrecargar la propiedad .

En C#, esta característica se denomina indexador y no se puede hacer referencia por nombre. De forma predeterminada, un indexador de C# aparece en los metadatos como una propiedad indizada denominada "Item". Sin embargo, un desarrollador de biblioteca de clases puede usar el IndexerNameAttribute atributo para cambiar el nombre del indexador en los metadatos. Por ejemplo, la String clase tiene un indexador denominado Chars[]. Las propiedades indizada creadas mediante lenguajes distintos de C# también pueden tener nombres distintos de Item.

Para determinar si un tipo tiene una propiedad predeterminada, use el GetCustomAttributes(Type, Boolean) método para probar el DefaultMemberAttribute atributo. Si el tipo tiene DefaultMemberAttribute, la MemberName propiedad devuelve el nombre de la propiedad predeterminada.

Consulte también

Se aplica a

GetProperty(String, Type, Type[], ParameterModifier[])

Busca la propiedad pública especificada cuyos parámetros coincidan con los tipos y modificadores de los argumentos especificados.

public:
 System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public:
 virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ types, cli::array <System::Reflection::ParameterModifier> ^ modifiers);
public System.Reflection.PropertyInfo? GetProperty (string name, Type? returnType, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
public System.Reflection.PropertyInfo GetProperty (string name, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers);
member this.GetProperty : string * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
abstract member GetProperty : string * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type * Type[] * System.Reflection.ParameterModifier[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, returnType As Type, types As Type(), modifiers As ParameterModifier()) As PropertyInfo

Parámetros

name
String

Cadena que contiene el nombre de la propiedad pública que se va a obtener.

returnType
Type

Tipo de valor devuelto de la propiedad.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que la propiedad indizada debe obtener.

O bien

Matriz vacía del tipo Type (es decir, Type[] types = new Type[0]) para obtener una propiedad que no esté indizada.

modifiers
ParameterModifier[]

Matriz de objetos ParameterModifier que representan los atributos asociados al elemento correspondiente de la matriz types. El enlazador predeterminado no procesa este parámetro.

Devoluciones

PropertyInfo

Objeto que representa la propiedad pública que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Existe más de una propiedad con el nombre especificado que coincide con los modificadores y tipos de argumentos especificados.

name es null.

O bien

types es null.

types es multidimensional.

O bien

modifiers es multidimensional.

O bien

types y modifiers no tienen la misma longitud.

Un elemento de types es null.

Ejemplos

En el ejemplo siguiente se obtiene un Type objeto correspondiente a MyPropertyClassy la propiedad indizada de esta clase se recupera mediante los argumentos pasados al GetProperty método .

using namespace System;
using namespace System::Reflection;
public ref class MyPropertyClass
{
private:
   array<int, 2>^ myPropertyArray;

public:

   property int Item [int, int]
   {
      // Declare an indexer.
      int get( int i, int j )
      {
         return myPropertyArray[ i,j ];
      }

      void set( int i, int j, int value )
      {
         myPropertyArray[ i,j ] = value;
      }

   }

};

int main()
{
   try
   {
      Type^ myType = MyPropertyClass::typeid;
      array<Type^>^myTypeArray = gcnew array<Type^>(2);
      
      // Create an instance of the Type array representing the number, order
      // and type of the parameters for the property.
      myTypeArray->SetValue( int::typeid, 0 );
      myTypeArray->SetValue( int::typeid, 1 );
      
      // Search for the indexed property whose parameters match the
      // specified argument types and modifiers.
      PropertyInfo^ myPropertyInfo = myType->GetProperty( "Item", int::typeid, myTypeArray, nullptr );
      Console::WriteLine( "{0}.{1} has a property type of {2}", myType->FullName, myPropertyInfo->Name, myPropertyInfo->PropertyType );
   }
   catch ( Exception^ ex ) 
   {
      Console::WriteLine( "An exception occurred {0}", ex->Message );
   }

}
using System;
using System.Reflection;
public class MyPropertyClass
{
    private int [,] myPropertyArray = new int[10,10];
    // Declare an indexer.
    public int this [int i,int j]
    {
        get
        {
            return myPropertyArray[i,j];
        }
        set
        {
            myPropertyArray[i,j] = value;
        }
    }
}
public class MyTypeClass
{
    public static void Main()
    {
        try
        {
            Type myType=typeof(MyPropertyClass);
            Type[] myTypeArray = new Type[2];
            // Create an instance of the Type array representing the number, order
            // and type of the parameters for the property.
            myTypeArray.SetValue(typeof(int),0);
            myTypeArray.SetValue(typeof(int),1);
            // Search for the indexed property whose parameters match the
            // specified argument types and modifiers.
            PropertyInfo myPropertyInfo = myType.GetProperty("Item",
                typeof(int),myTypeArray,null);
            Console.WriteLine(myType.FullName + "." + myPropertyInfo.Name +
                " has a property type of " + myPropertyInfo.PropertyType);
         }
        catch(Exception ex)
        {
            Console.WriteLine("An exception occurred " + ex.Message);
        }
    }
}
open System

type MyPropertyClass() =
    let myPropertyArray = Array2D.zeroCreate<int> 10 10
    // Declare an indexed property.
    member _.Item
        with get (i, j) =
            myPropertyArray[i, j]
        and set (i, j) value =
            myPropertyArray[i, j] <- value

try
    let myType = typeof<MyPropertyClass>
    let myTypeArray = Array.zeroCreate<Type> 2
    // Create an instance of the Type array representing the number, order
    // and type of the parameters for the property.
    myTypeArray.SetValue(typeof<int>, 0)
    myTypeArray.SetValue(typeof<int>, 1)
    // Search for the indexed property whose parameters match the
    // specified argument types and modifiers.
    let myPropertyInfo = myType.GetProperty("Item", typeof<int>, myTypeArray, null)
    printfn $"{myType.FullName}.{myPropertyInfo.Name} has a property type of {myPropertyInfo.PropertyType}"
with ex ->
    printfn $"An exception occurred {ex.Message}"
Imports System.Reflection

Public Class MyPropertyClass
    Private myPropertyArray(9, 9) As Integer
    ' Declare an indexer.
    Default Public Property Item(ByVal i As Integer, ByVal j As Integer) As Integer
        Get
            Return myPropertyArray(i, j)
        End Get
        Set(ByVal Value As Integer)
            myPropertyArray(i, j) = Value
        End Set
    End Property
End Class

Public Class MyTypeClass
    Public Shared Sub Main()
        Try
            Dim myType As Type = GetType(MyPropertyClass)
            Dim myTypeArray(1) As Type
            ' Create an instance of a Type array representing the number, order 
            ' and type of the parameters for the property.
            myTypeArray.SetValue(GetType(Integer), 0)
            myTypeArray.SetValue(GetType(Integer), 1)
            ' Search for the indexed property whose parameters match the
            ' specified argument types and modifiers.
            Dim myPropertyInfo As PropertyInfo = myType.GetProperty("Item", _
                  GetType(Integer), myTypeArray, Nothing)
            Console.WriteLine(myType.FullName + "." + myPropertyInfo.Name + _
                  " has a property  type of " + myPropertyInfo.PropertyType.ToString())
        Catch ex As Exception
            Console.WriteLine("An exception occurred " + ex.Message.ToString())
        End Try
    End Sub
End Class

Comentarios

Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso público. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (en Visual Basic, combinar los valores mediante Or) para obtenerla.

Aunque el enlazador predeterminado no procesa ParameterModifier (el modifiers parámetro ), puede usar la clase abstracta System.Reflection.Binder para escribir un enlazador personalizado que procese modifiers. ParameterModifier solo se usa al llamar a través de la interoperabilidad COM y solo se controlan los parámetros que se pasan por referencia.

La búsqueda distingue name mayúsculas de minúsculas. La búsqueda incluye propiedades de instancia pública estática y pública.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con PropertyInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en las propiedades de la restricción de clase.

Indizadores y propiedades predeterminadas

Visual Basic 2005, Visual C# 2005 y Visual C++ 2005 tienen una sintaxis simplificada para acceder a las propiedades indizada y permiten que una propiedad indexada sea un valor predeterminado para su tipo. Por ejemplo, si la variable myList hace referencia a ArrayList, la sintaxis myList[3] (myList(3) en Visual Basic) recupera el elemento con el índice de 3. Puede sobrecargar la propiedad .

En C#, esta característica se denomina indexador y no se puede hacer referencia por nombre. De forma predeterminada, un indexador de C# aparece en los metadatos como una propiedad indizada denominada "Item". Sin embargo, un desarrollador de biblioteca de clases puede usar el IndexerNameAttribute atributo para cambiar el nombre del indexador en los metadatos. Por ejemplo, la String clase tiene un indexador denominado Chars[]. Las propiedades indizada creadas mediante lenguajes distintos de C# también pueden tener nombres distintos de Item.

Para determinar si un tipo tiene una propiedad predeterminada, use el GetCustomAttributes(Type, Boolean) método para probar el DefaultMemberAttribute atributo. Si el tipo tiene DefaultMemberAttribute, la MemberName propiedad devuelve el nombre de la propiedad predeterminada.

Consulte también

Se aplica a

GetProperty(String, Type[])

Busca la propiedad pública especificada cuyos parámetros coincidan con los tipos de argumentos especificados.

public:
 System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, cli::array <Type ^> ^ types);
public:
 virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, cli::array <Type ^> ^ types);
public System.Reflection.PropertyInfo? GetProperty (string name, Type[] types);
public System.Reflection.PropertyInfo GetProperty (string name, Type[] types);
member this.GetProperty : string * Type[] -> System.Reflection.PropertyInfo
abstract member GetProperty : string * Type[] -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type[] -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, types As Type()) As PropertyInfo

Parámetros

name
String

Cadena que contiene el nombre de la propiedad pública que se va a obtener.

types
Type[]

Matriz de objetos Type que representa el número, el orden y el tipo de parámetros que la propiedad indizada debe obtener.

O bien

Matriz vacía del tipo Type (es decir, Type[] types = new Type[0]) para obtener una propiedad que no esté indizada.

Devoluciones

PropertyInfo

Objeto que representa la propiedad pública cuyos parámetros coinciden con los tipos de argumentos especificados, si se encuentra; en caso contrario, null.

Implementaciones

Excepciones

Se encontró más de una propiedad con el nombre especificado y que coincide con los tipos de argumento especificados.

name es null.

O bien

types es null.

types es multidimensional.

Un elemento de types es null.

Ejemplos

En el ejemplo siguiente se recupera el objeto de una clase definida por el Type usuario, se recupera la propiedad de esa clase y se muestra el nombre de propiedad y el tipo de la propiedad tal y como especifican los argumentos pasados a GetProperty.

using namespace System;
using namespace System::Reflection;
ref class MyClass1
{
private:
   array<int, 2>^myArray;

public:

   property int Item [int, int]
   {

      // Declare an indexer.
      int get( int i, int j )
      {
         return myArray[ i,j ];
      }

      void set( int i, int j, int value )
      {
         myArray[ i,j ] = value;
      }

   }

};

int main()
{
   try
   {
      
      // Get the Type object.
      Type^ myType = MyClass1::typeid;
      array<Type^>^myTypeArr = gcnew array<Type^>(2);
      
      // Create an instance of a Type array.
      myTypeArr->SetValue( int::typeid, 0 );
      myTypeArr->SetValue( int::typeid, 1 );
      
      // Get the PropertyInfo object for the indexed property Item, which has two integer parameters.
      PropertyInfo^ myPropInfo = myType->GetProperty( "Item", myTypeArr );
      
      // Display the property.
      Console::WriteLine( "The {0} property exists in MyClass1.", myPropInfo );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine( "An exception occurred." );
      Console::WriteLine( "Source : {0}", e->Source );
      Console::WriteLine( "Message : {0}", e->Message );
   }

}

using System;
using System.Reflection;
class MyClass1
{
    private int [,] myArray = {{1,2},{3,4}};
    // Declare an indexer.
    public int this [int i,int j]
    {
        get
        {
            return myArray[i,j];
        }
        set
        {
            myArray[i,j] = value;
        }
    }
}
public class MyTypeClass
{
    public static void Main(string[] args)
    {
        try
        {
            // Get the Type object.
            Type myType=typeof(MyClass1);
            Type[] myTypeArr = new Type[2];
            // Create an instance of a Type array.
            myTypeArr.SetValue(typeof(int),0);
            myTypeArr.SetValue(typeof(int),1);
            // Get the PropertyInfo object for the indexed property Item, which has two integer parameters.
            PropertyInfo myPropInfo = myType.GetProperty("Item", myTypeArr);
            // Display the property.
            Console.WriteLine("The {0} property exists in MyClass1.", myPropInfo.ToString());
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine("An exception occurred.");
            Console.WriteLine("Source : {0}" , e.Source);
            Console.WriteLine("Message : {0}" , e.Message);
        }
    }
}
open System

type MyClass1() =
    let myArray = array2D [[1; 2]; [3; 4]]
    // Declare an indexed property.
    member _.Item
        with get (i, j) =
            myArray[i, j]
        and set (i, j) value =
            myArray[i, j] <- value
try
    // Get the Type object.
    let myType = typeof<MyClass1>
    let myTypeArr = Array.zeroCreate<Type> 2
    // Create an instance of a Type array.
    myTypeArr.SetValue(typeof<int>, 0)
    myTypeArr.SetValue(typeof<int>, 1)
    // Get the PropertyInfo object for the indexed property Item, which has two integer parameters.
    let myPropInfo = myType.GetProperty("Item", myTypeArr)
    // Display the property.
    printfn $"The {myPropInfo} property exists in MyClass1."
with :? NullReferenceException as e ->
    printfn "An exception occurred."
    printfn $"Source : {e.Source}" 
    printfn $"Message : {e.Message}"
Imports System.Reflection

Module Module1
    Class MyClass1
        Private myArray As Integer(,) = {{1, 2}, {3, 4}}
        ' Declare an indexer.
        Default Public Property Item(ByVal i As Integer, ByVal j As Integer) As Integer
            Get
                Return myArray(i, j)
            End Get
            Set(ByVal Value As Integer)

                myArray(i, j) = Value
            End Set
        End Property
    End Class

    Public Class MyTypeClass
        Public Shared Sub Main()
            Try
                ' Get the Type Object.
                Dim myType As Type = GetType(MyClass1)
                Dim myTypeArr(1) As Type
                ' Create an instance of a Type array.
                myTypeArr.SetValue(GetType(Integer), 0)
                myTypeArr.SetValue(GetType(Integer), 1)
                ' Get the PropertyInfo object for the indexed property Item, which has two integer parameters. 
                Dim myPropInfo As PropertyInfo = myType.GetProperty("Item", myTypeArr)
                ' Display the property.
                Console.WriteLine("The {0} property exists in MyClass1.", myPropInfo.ToString())
            Catch e As NullReferenceException
                Console.WriteLine("An exception occurred.")
                Console.WriteLine("Source : {0}", e.Source.ToString())
                Console.WriteLine("Message : {0}", e.Message.ToString())
            End Try
        End Sub
    End Class
End Module 'Module1

Comentarios

Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso público. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (en Visual Basic, combinar los valores mediante Or) para obtenerla.

La búsqueda distingue name mayúsculas de minúsculas. La búsqueda incluye propiedades de instancia pública estática y pública.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con PropertyInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en las propiedades de la restricción de clase.

Indizadores y propiedades predeterminadas

Visual Basic 2005, Visual C# 2005 y Visual C++ 2005 tienen una sintaxis simplificada para acceder a las propiedades indizada y permiten que una propiedad indexada sea un valor predeterminado para su tipo. Por ejemplo, si la variable myList hace referencia a ArrayList, la sintaxis myList[3] (myList(3) en Visual Basic) recupera el elemento con el índice de 3. Puede sobrecargar la propiedad .

En C#, esta característica se denomina indexador y no se puede hacer referencia por nombre. De forma predeterminada, un indexador de C# aparece en los metadatos como una propiedad indizada denominada "Item". Sin embargo, un desarrollador de biblioteca de clases puede usar el IndexerNameAttribute atributo para cambiar el nombre del indexador en los metadatos. Por ejemplo, la String clase tiene un indexador denominado Chars[]. Las propiedades indizada creadas mediante lenguajes distintos de C# también pueden tener nombres distintos de Item.

Para determinar si un tipo tiene una propiedad predeterminada, use el GetCustomAttributes(Type, Boolean) método para probar el DefaultMemberAttribute atributo. Si el tipo tiene DefaultMemberAttribute, la MemberName propiedad devuelve el nombre de la propiedad predeterminada.

Consulte también

Se aplica a

GetProperty(String, Type)

Busca la propiedad pública con el nombre especificado y el tipo de valor devuelto.

public:
 System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType);
public:
 virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, Type ^ returnType);
public System.Reflection.PropertyInfo? GetProperty (string name, Type? returnType);
public System.Reflection.PropertyInfo GetProperty (string name, Type returnType);
member this.GetProperty : string * Type -> System.Reflection.PropertyInfo
abstract member GetProperty : string * Type -> System.Reflection.PropertyInfo
override this.GetProperty : string * Type -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, returnType As Type) As PropertyInfo

Parámetros

name
String

Cadena que contiene el nombre de la propiedad pública que se va a obtener.

returnType
Type

Tipo de valor devuelto de la propiedad.

Devoluciones

PropertyInfo

Objeto que representa la propiedad pública con el nombre especificado, si se encuentra; en caso contrario, null.

Implementaciones

Excepciones

Se encontró más de una propiedad con el nombre especificado.

name es null o returnType es null.

Ejemplos

En el ejemplo siguiente se define una clase con una propiedad y se recupera el nombre y el tipo de la propiedad.

using namespace System;
using namespace System::Reflection;
ref class MyClass1
{
private:
   String^ myMessage;

public:

   property String^ MyProperty1 
   {
      String^ get()
      {
         return myMessage;
      }

      void set( String^ value )
      {
         myMessage = value;
      }
   }
};

int main()
{
   try
   {
      Type^ myType = MyClass1::typeid;
      
      // Get the PropertyInfo Object* representing MyProperty1.
      PropertyInfo^ myStringProperties1 = myType->GetProperty( "MyProperty1", String::typeid );
      Console::WriteLine( "The name of the first property of MyClass1 is {0}.", myStringProperties1->Name );
      Console::WriteLine( "The type of the first property of MyClass1 is {0}.", myStringProperties1->PropertyType );
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "ArgumentNullException : {0}", e->Message );
   }
   catch ( AmbiguousMatchException^ e ) 
   {
      Console::WriteLine( "AmbiguousMatchException : {0}", e->Message );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine( "Source : {0}", e->Source );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   //Output:
   //The name of the first property of MyClass1 is MyProperty1.
   //The type of the first property of MyClass1 is System.String.

}

using System;
using System.Reflection;

class MyClass1
{
    String myMessage="Hello World.";
    public string MyProperty1
    {
        get
        {			
            return myMessage;
        }
        set
        {
            myMessage =value;
        }			
    }
}
class TestClass
{
    static void Main()
    {
        try
        {	
            Type myType = typeof(MyClass1);
            // Get the PropertyInfo object representing MyProperty1.
            PropertyInfo myStringProperties1 = myType.GetProperty("MyProperty1",
                typeof(string));
            Console.WriteLine("The name of the first property of MyClass1 is {0}.", myStringProperties1.Name);
            Console.WriteLine("The type of the first property of MyClass1 is {0}.", myStringProperties1.PropertyType);
        }
        catch(ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException :"+e.Message);
        }
        catch(AmbiguousMatchException e)
        {
            Console.WriteLine("AmbiguousMatchException :"+e.Message);
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine("Source : {0}" , e.Source);
            Console.WriteLine("Message : {0}" , e.Message);
        }
    //Output:
    //The name of the first property of MyClass1 is MyProperty1.
    //The type of the first property of MyClass1 is System.String.
    }
}
open System
open System.Reflection

type MyClass1() =
    let mutable myMessage = "Hello World."
    member _.MyProperty1 
        with get () =
            myMessage
        and set (value) =
            myMessage <- value

try
    let myType = typeof<MyClass1>
    // Get the PropertyInfo object representing MyProperty1.
    let myStringProperties1 = myType.GetProperty("MyProperty1", typeof<string>)
    printfn $"The name of the first property of MyClass1 is {myStringProperties1.Name}."
    printfn $"The type of the first property of MyClass1 is {myStringProperties1.PropertyType}."
with
| :? ArgumentNullException as e ->
    printfn $"ArgumentNullException :{e.Message}"
| :? AmbiguousMatchException as e ->
    printfn $"AmbiguousMatchException :{e.Message}"
| :? NullReferenceException as e ->
    printfn $"Source : {e.Source}"
    printfn $"Message : {e.Message}"
// Output:
//     The name of the first property of MyClass1 is MyProperty1.
//     The type of the first property of MyClass1 is System.String.
Imports System.Reflection
Class MyClass1
    Private myMessage As [String] = "Hello World."
    Public Property MyProperty1() As String
        Get
            Return myMessage
        End Get
        Set(ByVal Value As String)
            myMessage = Value
        End Set
    End Property
End Class

Class TestClass
    Shared Sub Main()
        Try
            Dim myType As Type = GetType(MyClass1)
            ' Get the PropertyInfo object representing MyProperty1. 
            Dim myStringProperties1 As PropertyInfo = myType.GetProperty("MyProperty1", GetType(String))
            Console.WriteLine("The name of the first property of MyClass1 is {0}.", myStringProperties1.Name)
            Console.WriteLine("The type of the first property of MyClass1 is {0}.", myStringProperties1.PropertyType.ToString())
        Catch e As ArgumentNullException
            Console.WriteLine("ArgumentNullException :" + e.Message.ToString())
        Catch e As AmbiguousMatchException
            Console.WriteLine("AmbiguousMatchException :" + e.Message.ToString())
        Catch e As NullReferenceException
            Console.WriteLine("Source : {0}", e.Source.ToString())
            Console.WriteLine("Message : {0}", e.Message.ToString())
        End Try
    'Output:
    'The name of the first property of MyClass1 is MyProperty1.
    'The type of the first property of MyClass1 is System.String.

    End Sub
End Class

Comentarios

Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso público. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (en Visual Basic, combinar los valores mediante Or) para obtenerla.

La búsqueda distingue name mayúsculas de minúsculas. La búsqueda incluye propiedades de instancia pública estática y pública.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con PropertyInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en las propiedades de la restricción de clase.

Indizadores y propiedades predeterminadas

Visual Basic 2005, Visual C# 2005 y Visual C++ 2005 tienen una sintaxis simplificada para acceder a las propiedades indizada y permiten que una propiedad indexada sea un valor predeterminado para su tipo. Por ejemplo, si la variable myList hace referencia a ArrayList, la sintaxis myList[3] (myList(3) en Visual Basic) recupera el elemento con el índice de 3. Puede sobrecargar la propiedad .

En C#, esta característica se denomina indexador y no se puede hacer referencia por nombre. De forma predeterminada, un indexador de C# aparece en los metadatos como una propiedad indizada denominada "Item". Sin embargo, un desarrollador de biblioteca de clases puede usar el IndexerNameAttribute atributo para cambiar el nombre del indexador en los metadatos. Por ejemplo, la String clase tiene un indexador denominado Chars[]. Las propiedades indizada creadas mediante lenguajes distintos de C# también pueden tener nombres distintos de Item.

Para determinar si un tipo tiene una propiedad predeterminada, use el GetCustomAttributes(Type, Boolean) método para probar el DefaultMemberAttribute atributo. Si el tipo tiene DefaultMemberAttribute, la MemberName propiedad devuelve el nombre de la propiedad predeterminada.

Consulte también

Se aplica a

GetProperty(String, BindingFlags)

Busca la propiedad especificada, mediante las restricciones de enlace especificadas.

public:
 virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
public System.Reflection.PropertyInfo? GetProperty (string name, System.Reflection.BindingFlags bindingAttr);
public System.Reflection.PropertyInfo GetProperty (string name, System.Reflection.BindingFlags bindingAttr);
abstract member GetProperty : string * System.Reflection.BindingFlags -> System.Reflection.PropertyInfo
override this.GetProperty : string * System.Reflection.BindingFlags -> System.Reflection.PropertyInfo
Public Function GetProperty (name As String, bindingAttr As BindingFlags) As PropertyInfo

Parámetros

name
String

Cadena que contiene el nombre de la propiedad que se va a obtener.

bindingAttr
BindingFlags

Combinación bit a bit de los valores de enumeración que especifican cómo se realiza la búsqueda.

O bien

Default para devolver null.

Devoluciones

PropertyInfo

Objeto que representa la propiedad que cumple los requisitos especificados, si se encuentra; en caso contrario, es null.

Implementaciones

Excepciones

Se encontró más de una propiedad con el nombre especificado y que coincide con las restricciones de enlace especificadas.

name es null.

Ejemplos

En el ejemplo siguiente se recupera el tipo de una clase definida por el usuario, se recupera una propiedad de esa clase y se muestra el nombre de propiedad de acuerdo con las restricciones de enlace especificadas.

using namespace System;
using namespace System::Reflection;
ref class MyClass
{
private:
   int myProperty;

public:

   property int MyProperty 
   {
      // Declare MyProperty.
      int get()
      {
         return myProperty;
      }

      void set( int value )
      {
         myProperty = value;
      }
   }
};

int main()
{
   try
   {
      // Get Type object of MyClass.
      Type^ myType = MyClass::typeid;
      
      // Get the PropertyInfo by passing the property name and specifying the BindingFlags.
      PropertyInfo^ myPropInfo = myType->GetProperty( "MyProperty", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
      
      // Display Name propety to console.
      Console::WriteLine( "{0} is a property of MyClass.", myPropInfo->Name );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine( "MyProperty does not exist in MyClass. {0}", e->Message );
   }
}

using System;
using System.Reflection;
class MyClass
{
    private int myProperty;
    // Declare MyProperty.
    public int MyProperty
    {
        get
        {
            return myProperty;
        }
        set
        {
            myProperty=value;
        }
    }
}
public class MyTypeClass
{
    public static void Main(string[] args)
    {
        try
        {
            // Get Type object of MyClass.
            Type myType=typeof(MyClass);
            // Get the PropertyInfo by passing the property name and specifying the BindingFlags.
            PropertyInfo myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.Instance);
            // Display Name propety to console.
            Console.WriteLine("{0} is a property of MyClass.", myPropInfo.Name);
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine("MyProperty does not exist in MyClass." +e.Message);
        }
    }
}
open System
open System.Reflection

type MyClass() =
    let mutable myProperty = 0
    // Declare MyProperty.
    member _.MyProperty
        with get () =
            myProperty
        and set (value) =
            myProperty <- value

try
    // Get Type object of MyClass.
    let myType = typeof<MyClass>
    // Get the PropertyInfo by passing the property name and specifying the BindingFlags.
    let myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public ||| BindingFlags.Instance)
    // Display Name propety to console.
    printfn $"{myPropInfo.Name} is a property of MyClass."
with :? NullReferenceException as e ->
    printfn $"MyProperty does not exist in MyClass.{e.Message}"

Imports System.Reflection
Module Module1
    Public Class MyClass1
        Private myProperty1 As Integer
        ' Declare MyProperty.
        Public Property MyProperty() As Integer
            Get
                Return myProperty1
            End Get
            Set(ByVal Value As Integer)
                myProperty1 = Value
            End Set
        End Property
        Public Shared Sub Main()
            Try
                ' Get a Type object corresponding to MyClass.
                Dim myType As Type = GetType(MyClass1)
                ' Get a PropertyInfo object by passing property name and specifying BindingFlags.
                Dim myPropInfo As PropertyInfo = myType.GetProperty("MyProperty", BindingFlags.Public Or BindingFlags.Instance)
                ' Display the Name property.
                Console.WriteLine("{0} is a property of MyClass.", myPropInfo.Name)
            Catch e As NullReferenceException
                Console.WriteLine("MyProperty does not exist in MyClass.", e.Message.ToString())
            End Try
        End Sub
    End Class
End Module 'Module1

Comentarios

Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso público. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (en Visual Basic, combinar los valores mediante Or) para obtenerla.

Las marcas de filtro siguientes BindingFlags se pueden usar para definir qué propiedades se van a incluir en la búsqueda:

  • Debe especificar o BindingFlags.InstanceBindingFlags.Static para obtener una devolución.

  • Especifique BindingFlags.Public para incluir propiedades públicas en la búsqueda.

  • Especifique BindingFlags.NonPublic que incluya propiedades no públicas (es decir, propiedades privadas, internas y protegidas) en la búsqueda.

  • Especifique BindingFlags.FlattenHierarchy para incluir y protected miembros public estáticos en la jerarquía; private no se incluyen los miembros estáticos de las clases heredadas.

Se pueden usar las marcas modificadores siguientes BindingFlags para cambiar el funcionamiento de la búsqueda:

  • BindingFlags.IgnoreCase para pasar por alto el caso de name.

  • BindingFlags.DeclaredOnly para buscar solo las propiedades declaradas en , Typeno las propiedades que simplemente se heredaron.

Vea System.Reflection.BindingFlags para obtener más información.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con PropertyInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en las propiedades de la restricción de clase.

Entre las situaciones en las que AmbiguousMatchException se produce se incluyen las siguientes:

  • Un tipo contiene dos propiedades indizada que tienen el mismo nombre, pero distintos números de parámetros. Para resolver la ambigüedad, use una sobrecarga del GetProperty método que especifica los tipos de parámetro.

  • Un tipo derivado declara una propiedad que oculta una propiedad heredada con el mismo nombre, utilizando el new modificador (Shadows en Visual Basic). Para resolver la ambigüedad, incluya BindingFlags.DeclaredOnly para restringir la búsqueda a los miembros que no se heredan.

Indizadores y propiedades predeterminadas

Visual Basic 2005, Visual C# 2005 y Visual C++ 2005 tienen una sintaxis simplificada para acceder a las propiedades indizada y permiten que una propiedad indexada sea un valor predeterminado para su tipo. Por ejemplo, si la variable myList hace referencia a ArrayList, la sintaxis myList[3] (myList(3) en Visual Basic) recupera el elemento con el índice de 3. Puede sobrecargar la propiedad .

En C#, esta característica se denomina indexador y no se puede hacer referencia por nombre. De forma predeterminada, un indexador de C# aparece en los metadatos como una propiedad indizada denominada "Item". Sin embargo, un desarrollador de biblioteca de clases puede usar el IndexerNameAttribute atributo para cambiar el nombre del indexador en los metadatos. Por ejemplo, la String clase tiene un indexador denominado Chars[]. Las propiedades indizada creadas mediante lenguajes distintos de C# también pueden tener nombres distintos de Item.

Para determinar si un tipo tiene una propiedad predeterminada, use el GetCustomAttributes(Type, Boolean) método para probar el DefaultMemberAttribute atributo. Si el tipo tiene DefaultMemberAttribute, la MemberName propiedad devuelve el nombre de la propiedad predeterminada.

Consulte también

Se aplica a

GetProperty(String)

Busca la propiedad pública con el nombre especificado.

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

Parámetros

name
String

Cadena que contiene el nombre de la propiedad pública que se va a obtener.

Devoluciones

PropertyInfo

Objeto que representa la propiedad pública con el nombre especificado, si se encuentra; en caso contrario, null.

Implementaciones

Excepciones

Se encontró más de una propiedad con el nombre especificado.

name es null.

Ejemplos

En el ejemplo siguiente se recupera el objeto de una clase definida por el Type usuario, se recupera una propiedad de esa clase y se muestra el nombre de la propiedad.

using namespace System;
using namespace System::Reflection;
ref class MyClass
{
private:
   int myProperty;

public:

   property int MyProperty 
   {
      // Declare MyProperty.
      int get()
      {
         return myProperty;
      }

      void set( int value )
      {
         myProperty = value;
      }
   }
};

int main()
{
   try
   {
      // Get the Type object corresponding to MyClass.
      Type^ myType = MyClass::typeid;
      
      // Get the PropertyInfo object by passing the property name.
      PropertyInfo^ myPropInfo = myType->GetProperty( "MyProperty" );
      
      // Display the property name.
      Console::WriteLine( "The {0} property exists in MyClass.", myPropInfo->Name );
   }
   catch ( NullReferenceException^ e ) 
   {
      Console::WriteLine( "The property does not exist in MyClass. {0}", e->Message );
   }
}

using System;
using System.Reflection;

class MyClass
{
    private int myProperty;
    // Declare MyProperty.
    public int MyProperty
    {
        get
        {
            return myProperty;
        }
        set
        {
            myProperty=value;
        }
    }
}
public class MyTypeClass
{
    public static void Main(string[] args)
    {
        try
        {
            // Get the Type object corresponding to MyClass.
            Type myType=typeof(MyClass);
            // Get the PropertyInfo object by passing the property name.
            PropertyInfo myPropInfo = myType.GetProperty("MyProperty");
            // Display the property name.
            Console.WriteLine("The {0} property exists in MyClass.", myPropInfo.Name);
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine("The property does not exist in MyClass." + e.Message);
        }
    }
}
open System

type MyClass() =
    let mutable myProperty = 0
    // Declare MyProperty.
    member _.MyProperty
        with get () =
            myProperty
        and set (value) = 
            myProperty <- value

try
    // Get the Type object corresponding to MyClass.
    let myType = typeof<MyClass>
    // Get the PropertyInfo object by passing the property name.
    let myPropInfo = myType.GetProperty "MyProperty"
    // Display the property name.
    printfn $"The {myPropInfo.Name} property exists in MyClass."
with :? NullReferenceException as e ->
    printfn $"The property does not exist in MyClass.{e.Message}"
Imports System.Reflection
Class MyClass1
    Private myProperty1 As Integer
    ' Declare MyProperty.

    Public Property MyProperty() As Integer
        Get
            Return myProperty1
        End Get
        Set(ByVal Value As Integer)
            myProperty1 = Value
        End Set
    End Property
End Class

Public Class MyTypeClass
    Public Shared Sub Main(ByVal args() As String)
        Try
            ' Get Type Object corresponding to MyClass.
            Dim myType As Type = GetType(MyClass1)
            ' Get PropertyInfo object by passing property name.
            Dim myPropInfo As PropertyInfo = myType.GetProperty("MyProperty")
            ' Display Name propety to console.
            Console.WriteLine("The {0} property exists in MyClass.", myPropInfo.Name)
        Catch e As NullReferenceException
            Console.WriteLine("The property does not exist in MyClass.", e.Message.ToString())
        End Try
    End Sub
End Class

Internamente, esta propiedad se conoce en los metadatos por el nombre "Item". Cualquier intento de obtener PropertyInfo la reflexión debe especificar este nombre interno para devolver correctamente la PropertyInfo propiedad.

Comentarios

La búsqueda distingue name mayúsculas de minúsculas. La búsqueda incluye propiedades de instancia pública estática y pública.

Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso público. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (en Visual Basic, combinar los valores mediante Or) para obtenerla.

Si el objeto actual Type representa un tipo genérico construido, este método devuelve con PropertyInfo los parámetros de tipo reemplazados por los argumentos de tipo adecuados.

Si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico o un método genérico, este método busca en las propiedades de la restricción de clase.

Entre las situaciones en las que AmbiguousMatchException se produce se incluyen las siguientes:

  • Un tipo contiene dos propiedades indizada que tienen el mismo nombre, pero distintos números de parámetros. Para resolver la ambigüedad, use una sobrecarga del GetProperty método que especifica los tipos de parámetro.

  • Un tipo derivado declara una propiedad que oculta una propiedad heredada con el mismo nombre mediante el new modificador (Shadows en Visual Basic). Para resolver la ambigüedad, use la sobrecarga del GetProperty(String, BindingFlags) método y agregue la BindingFlags.DeclaredOnly marca para restringir la búsqueda a los miembros que no se heredan.

Indizadores y propiedades predeterminadas

Visual Basic 2005, Visual C# 2005 y Visual C++ 2005 tienen una sintaxis simplificada para acceder a las propiedades indizada y permiten que una propiedad indexada sea un valor predeterminado para su tipo. Por ejemplo, si la variable myList hace referencia a ArrayList, la sintaxis myList[3] (myList(3) en Visual Basic) recupera el elemento con el índice de 3. Puede sobrecargar la propiedad .

En C#, esta característica se denomina indexador y no se puede hacer referencia por nombre. De forma predeterminada, un indexador de C# aparece en los metadatos como una propiedad indizada denominada "Item". Sin embargo, un desarrollador de biblioteca de clases puede usar el IndexerNameAttribute atributo para cambiar el nombre del indexador en los metadatos. Por ejemplo, la String clase tiene un indexador denominado Chars[]. Las propiedades indizada creadas mediante lenguajes distintos de C# también pueden tener nombres distintos de Item.

Para determinar si un tipo tiene una propiedad predeterminada, use el GetCustomAttributes(Type, Boolean) método para probar el DefaultMemberAttribute atributo. Si el tipo tiene DefaultMemberAttribute, la MemberName propiedad devuelve el nombre de la propiedad predeterminada.

Consulte también

Se aplica a