Type.GetProperties Método
Definición
Sobrecargas
GetProperties() |
Devuelve todas las propiedades públicas del objeto Type actual.Returns all the public properties of the current Type. |
GetProperties(BindingFlags) |
Cuando se invalida en una clase derivada, busca las propiedades del objeto Type actual y aplica las restricciones de enlace especificadas.When overridden in a derived class, searches for the properties of the current Type, using the specified binding constraints. |
GetProperties()
public:
cli::array <System::Reflection::PropertyInfo ^> ^ GetProperties();
public:
virtual cli::array <System::Reflection::PropertyInfo ^> ^ GetProperties();
public System.Reflection.PropertyInfo[] GetProperties ();
member this.GetProperties : unit -> System.Reflection.PropertyInfo[]
abstract member GetProperties : unit -> System.Reflection.PropertyInfo[]
override this.GetProperties : unit -> System.Reflection.PropertyInfo[]
Public Function GetProperties () As PropertyInfo()
Devoluciones
Matriz de objetos PropertyInfo que representa todas las propiedades públicas del objeto Type actual.An array of PropertyInfo objects representing all public properties of the current Type.
o bien-or- Matriz vacía de tipo PropertyInfo si el objeto Type actual no tiene propiedades públicas.An empty array of type PropertyInfo, if the current Type does not have public properties.
Implementaciones
Ejemplos
En el siguiente ejemplo se muestra el uso del método GetProperties
.The following example demonstrates the use of the GetProperties
method.
array<PropertyInfo^>^myPropertyInfo;
// Get the properties of 'Type' class object.
myPropertyInfo = Type::GetType( "System.Type" )->GetProperties();
Console::WriteLine( "Properties of System.Type are:" );
for ( int i = 0; i < myPropertyInfo->Length; i++ )
{
Console::WriteLine( myPropertyInfo[ i ] );
}
PropertyInfo[] myPropertyInfo;
// Get the properties of 'Type' class object.
myPropertyInfo = Type.GetType("System.Type").GetProperties();
Console.WriteLine("Properties of System.Type are:");
for (int i = 0; i < myPropertyInfo.Length; i++)
{
Console.WriteLine(myPropertyInfo[i].ToString());
}
Dim myPropertyInfo() As PropertyInfo
' Get the properties of 'Type' class object.
myPropertyInfo = Type.GetType("System.Type").GetProperties()
Console.WriteLine("Properties of System.Type are:")
Dim i As Integer
For i = 0 To myPropertyInfo.Length - 1
Console.WriteLine(myPropertyInfo(i).ToString())
Next i
Comentarios
Llamar a esta sobrecarga es equivalente a llamar a la GetProperties(BindingFlags) sobrecarga con un bindingAttr
argumento igual a BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public
en C# y BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public
en Visual Basic.Calling this overload is equivalent to calling the GetProperties(BindingFlags) overload with a bindingAttr
argument equal to BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public
in C# and BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public
in Visual Basic. Devuelve todas las propiedades públicas y estáticas, tanto las definidas por el tipo representado por el Type objeto actual como las heredadas de sus tipos base.It returns all public instance and static properties, both those defined by the type represented by the current Type object as well as those inherited from its base types.
Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso que sea público.A property is considered public to reflection if it has at least one accessor that is public. De lo contrario, la propiedad se considera privada y debe usar BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static (en Visual Basic, combinar los valores mediante Or
) para obtenerlo.Otherwise the property 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 GetProperties método no devuelve las propiedades en un orden determinado, como el orden alfabético o de declaración.The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. El código no debe depender del orden en el que se devuelven las propiedades, ya que ese orden varía.Your code must not depend on the order in which properties are returned, because that order varies.
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 PropertyInfo 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 PropertyInfo 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 en las propiedades 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 properties of the class constraint.
Consulte también
Se aplica a
GetProperties(BindingFlags)
public:
abstract cli::array <System::Reflection::PropertyInfo ^> ^ GetProperties(System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);
abstract member GetProperties : System.Reflection.BindingFlags -> System.Reflection.PropertyInfo[]
Public MustOverride Function GetProperties (bindingAttr As BindingFlags) As PropertyInfo()
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 que representa todas las propiedades del objeto Type actual que coinciden con las restricciones de enlace especificadas.An array of objects representing all properties of the current Type that match the specified binding constraints.
o bien-or- Matriz vacía de tipo PropertyInfo si el objeto Type actual no tiene propiedades o si ninguna de las propiedades coincide con las restricciones de enlace.An empty array of type PropertyInfo, if the current Type does not have properties, or if none of the properties match the binding constraints.
Implementaciones
Ejemplos
En el ejemplo siguiente se define una clase denominada PropertyClass
que incluye seis propiedades: dos son públicas, una es privada, una está protegida, una es interna ( Friend
en Visual Basic) y otra es interna protegida ( Protected Friend
en Visual Basic).The following example defines a class named PropertyClass
that includes six properties: two are public, one is private, one is protected, one is internal (Friend
in Visual Basic), and one is protected internal (Protected Friend
in Visual Basic). A continuación, muestra información básica de la propiedad (el nombre y el tipo de la propiedad, si es de lectura/escritura y la visibilidad de sus get
set
descriptores de acceso y) para las propiedades que coinciden con las restricciones de enlace especificadas.It then displays some basic property information (the property name and type, whether it is read/write, and the visibility of its get
and set
accessors) for the properties that match the specified binding constraints.
using namespace System;
using namespace System::Reflection;
// Create a class having three properties.
public ref class PropertyClass
{
public:
property String^ Property1
{
String^ get()
{
return "hello";
}
}
property String^ Property2
{
String^ get()
{
return "hello";
}
}
protected:
property String^ Property3
{
String^ get()
{
return "hello";
}
}
private:
property int Property4
{
int get()
{
return 32;
}
}
internal:
property String^ Property5
{
String^ get()
{
return "value";
}
}
public protected:
property String^ Property6
{
String^ get()
{
return "value";
}
}
};
String^ GetVisibility(MethodInfo^ accessor)
{
if (accessor->IsPublic)
return "Public";
else if (accessor->IsPrivate)
return "Private";
else if (accessor->IsFamily)
return "Protected";
else if (accessor->IsAssembly)
return "Internal/Friend";
else
return "Protected Internal/Friend";
}
void DisplayPropertyInfo(array<PropertyInfo^>^ propInfos )
{
// Display information for all properties.
for each(PropertyInfo^ propInfo in propInfos) {
bool readable = propInfo->CanRead;
bool writable = propInfo->CanWrite;
Console::WriteLine(" Property name: {0}", propInfo->Name);
Console::WriteLine(" Property type: {0}", propInfo->PropertyType);
Console::WriteLine(" Read-Write: {0}", readable && writable);
if (readable) {
MethodInfo^ getAccessor = propInfo->GetMethod;
Console::WriteLine(" Visibility: {0}",
GetVisibility(getAccessor));
}
if (writable) {
MethodInfo^ setAccessor = propInfo->SetMethod;
Console::WriteLine(" Visibility: {0}",
GetVisibility(setAccessor));
}
Console::WriteLine();
}
}
void main()
{
Type^ myType = PropertyClass::typeid;
// Get the public properties.
array<PropertyInfo^>^propInfos = myType->GetProperties( static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
Console::WriteLine("The number of public properties: {0}.\n",
propInfos->Length);
// Display the public properties.
DisplayPropertyInfo( propInfos );
// Get the non-public properties.
array<PropertyInfo^>^propInfos1 = myType->GetProperties( static_cast<BindingFlags>(BindingFlags::NonPublic | BindingFlags::Instance) );
Console::WriteLine("The number of non-public properties: {0}.\n",
propInfos1->Length);
// Display all the non-public properties.
DisplayPropertyInfo(propInfos1);
}
// The example displays the following output:
// The number of public properties: 2.
//
// Property name: Property2
// Property type: System.String
// Read-Write: False
// Visibility: Public
//
// Property name: Property1
// Property type: System.String
// Read-Write: False
// Visibility: Public
//
// The number of non-public properties: 4.
//
// Property name: Property6
// Property type: System.String
// Read-Write: False
// Visibility: Protected Internal/Friend
//
// Property name: Property5
// Property type: System.String
// Read-Write: False
// Visibility: Internal/Friend
//
// Property name: Property4
// Property type: System.Int32
// Read-Write: False
// Visibility: Private
//
// Property name: Property3
// Property type: System.String
// Read-Write: False
// Visibility: Protected
using System;
using System.Reflection;
// Create a class having six properties.
public class PropertyClass
{
public String Property1
{
get { return "hello"; }
}
public String Property2
{
get { return "hello"; }
}
protected String Property3
{
get { return "hello"; }
}
private Int32 Property4
{
get { return 32; }
}
internal String Property5
{
get { return "value"; }
}
protected internal String Property6
{
get { return "value"; }
}
}
public class Example
{
public static void Main()
{
Type t = typeof(PropertyClass);
// Get the public properties.
PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public|BindingFlags.Instance);
Console.WriteLine("The number of public properties: {0}.\n",
propInfos.Length);
// Display the public properties.
DisplayPropertyInfo(propInfos);
// Get the nonpublic properties.
PropertyInfo[] propInfos1 = t.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);
Console.WriteLine("The number of non-public properties: {0}.\n",
propInfos1.Length);
// Display all the nonpublic properties.
DisplayPropertyInfo(propInfos1);
}
public static void DisplayPropertyInfo(PropertyInfo[] propInfos)
{
// Display information for all properties.
foreach (var propInfo in propInfos) {
bool readable = propInfo.CanRead;
bool writable = propInfo.CanWrite;
Console.WriteLine(" Property name: {0}", propInfo.Name);
Console.WriteLine(" Property type: {0}", propInfo.PropertyType);
Console.WriteLine(" Read-Write: {0}", readable & writable);
if (readable) {
MethodInfo getAccessor = propInfo.GetMethod;
Console.WriteLine(" Visibility: {0}",
GetVisibility(getAccessor));
}
if (writable) {
MethodInfo setAccessor = propInfo.SetMethod;
Console.WriteLine(" Visibility: {0}",
GetVisibility(setAccessor));
}
Console.WriteLine();
}
}
public static String GetVisibility(MethodInfo accessor)
{
if (accessor.IsPublic)
return "Public";
else if (accessor.IsPrivate)
return "Private";
else if (accessor.IsFamily)
return "Protected";
else if (accessor.IsAssembly)
return "Internal/Friend";
else
return "Protected Internal/Friend";
}
}
// The example displays the following output:
// The number of public properties: 2.
//
// Property name: Property1
// Property type: System.String
// Read-Write: False
// Visibility: Public
//
// Property name: Property2
// Property type: System.String
// Read-Write: False
// Visibility: Public
//
// The number of non-public properties: 4.
//
// Property name: Property3
// Property type: System.String
// Read-Write: False
// Visibility: Protected
//
// Property name: Property4
// Property type: System.Int32
// Read-Write: False
// Visibility: Private
//
// Property name: Property5
// Property type: System.String
// Read-Write: False
// Visibility: Internal/Friend
//
// Property name: Property6
// Property type: System.String
// Read-Write: False
// Visibility: Protected Internal/Friend
Imports System.Reflection
' Create a class having six properties.
Public Class PropertyClass
Public ReadOnly Property Property1() As String
Get
Return "hello"
End Get
End Property
Public ReadOnly Property Property2() As String
Get
Return "hello"
End Get
End Property
Protected ReadOnly Property Property3() As String
Get
Return "hello"
End Get
End Property
Private ReadOnly Property Property4 As Integer
Get
Return 32
End Get
End Property
Friend ReadOnly Property Property5 As String
Get
Return "value"
End Get
End Property
Protected Friend ReadOnly Property Property6 As String
Get
Return "value"
End Get
End Property
End Class
Public Module Example
Public Sub Main()
Dim t As Type = GetType(PropertyClass)
' Get the public properties.
Dim propInfos As PropertyInfo() = t.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
Console.WriteLine("The number of public properties: {0}",
propInfos.Length)
Console.WriteLine()
' Display the public properties.
DisplayPropertyInfo(propInfos)
' Get the non-public properties.
Dim propInfos1 As PropertyInfo() = t.GetProperties(BindingFlags.NonPublic Or BindingFlags.Instance)
Console.WriteLine("The number of non-public properties: {0}",
propInfos1.Length)
Console.WriteLine()
' Display all the non-public properties.
DisplayPropertyInfo(propInfos1)
End Sub
Public Sub DisplayPropertyInfo(ByVal propInfos() As PropertyInfo)
' Display information for all properties.
For Each propInfo In propInfos
Dim readable As Boolean = propInfo.CanRead
Dim writable As Boolean = propInfo.CanWrite
Console.WriteLine(" Property name: {0}", propInfo.Name)
Console.WriteLine(" Property type: {0}", propInfo.PropertyType)
Console.WriteLine(" Read-Write: {0}", readable And writable)
If readable Then
Dim getAccessor As MethodInfo = propInfo.GetMethod
Console.WriteLine(" Visibility: {0}",
GetVisibility(getAccessor))
End If
If writable Then
Dim setAccessor As MethodInfo = propInfo.SetMethod
Console.WriteLine(" Visibility: {0}",
GetVisibility(setAccessor))
End If
Console.WriteLine()
Next
End Sub
Public Function GetVisibility(accessor As MethodInfo) As String
If accessor.IsPublic Then
Return "Public"
ElseIf accessor.IsPrivate Then
Return "Private"
Else If accessor.IsFamily Then
Return "Protected"
Else If accessor.IsAssembly Then
Return "Internal/Friend"
Else
Return "Protected Internal/Friend"
End If
End Function
End Module
' The example displays the following output:
' The number of public properties: 2
'
' Property name: Property1
' Property type: System.String
' Read-Write: False
' Visibility: Public
'
' Property name: Property2
' Property type: System.String
' Read-Write: False
' Visibility: Public
'
' The number of non-public properties: 4
'
' Property name: Property3
' Property type: System.String
' Read-Write: False
' Visibility: Protected
'
' Property name: Property4
' Property type: System.Int32
' Read-Write: False
' Visibility: Private
'
' Property name: Property5
' Property type: System.String
' Read-Write: False
' Visibility: Internal/Friend
'
' Property name: Property6
' Property type: System.String
' Read-Write: False
' Visibility: Protected Internal/Friend
Comentarios
Para GetProperties(BindingFlags)
que la sobrecarga recupere correctamente la información de la propiedad, el bindingAttr
argumento debe incluir al menos una de BindingFlags.Instance y BindingFlags.Static , junto con al menos uno de BindingFlags.NonPublic y BindingFlags.Public .For the GetProperties(BindingFlags)
overload to successfully retrieve property information, the bindingAttr
argument must include at least one of BindingFlags.Instance and BindingFlags.Static, along with at least one of BindingFlags.NonPublic and BindingFlags.Public.
BindingFlagsSe pueden usar las siguientes marcas de filtro para definir las propiedades que se van a incluir en la búsqueda:The following BindingFlags filter flags can be used to define which properties to include in the search:
Especifique
BindingFlags.Instance
para incluir métodos de instancia.SpecifyBindingFlags.Instance
to include instance methods.Especifique
BindingFlags.Static
para incluir métodos estáticos.SpecifyBindingFlags.Static
to include static methods.Especifique
BindingFlags.Public
que se incluyan las propiedades públicas en la búsqueda.SpecifyBindingFlags.Public
to include public properties in the search. Una propiedad se considera pública para la reflexión si tiene al menos un descriptor de acceso que sea público.A property is considered public to reflection if it has at least one accessor that is public.Especifique
BindingFlags.NonPublic
que se incluyan propiedades no públicas (es decir, propiedades privadas, internas y protegidas) en la búsqueda.SpecifyBindingFlags.NonPublic
to include non-public properties (that is, private, internal, and protected properties) in the search. Solo se devuelven las propiedades protegidas e internas de las clases base; no se devuelven las propiedades privadas de las clases base.Only protected and internal properties on base classes are returned; private properties 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.Especifique
BindingFlags.Default
solo para devolver una PropertyInfo matriz vacía.SpecifyBindingFlags.Default
alone to return an empty PropertyInfo array.
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 las propiedades declaradas en Type , no las propiedades que se han heredado simplemente.BindingFlags.DeclaredOnly
to search only the properties declared on the Type, not properties that were simply inherited.
Vea System.Reflection.BindingFlags para obtener más información.See System.Reflection.BindingFlags for more information.
El GetProperties método no devuelve las propiedades en un orden determinado, como el orden alfabético o de declaración.The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. El código no debe depender del orden en el que se devuelven las propiedades, ya que ese orden varía.Your code must not depend on the order in which properties are returned, because that order varies.
Si el objeto actual Type representa un tipo genérico construido, este método devuelve los PropertyInfo 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 PropertyInfo 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 en las propiedades 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 properties of the class constraint.
Consulte también
- PropertyInfo
- BindingFlags
- DefaultBinder
- GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])