2009-02-10 22 views
146

Tengo una clase.¿Cómo recorrer todas las propiedades de una clase?

Public Class Foo 
    Private _Name As String 
    Public Property Name() As String 
     Get 
      Return _Name 
     End Get 
     Set(ByVal value As String) 
      _Name = value 
     End Set 
    End Property 

    Private _Age As String 
    Public Property Age() As String 
     Get 
      Return _Age 
     End Get 
     Set(ByVal value As String) 
      _Age = value 
     End Set 
    End Property 

    Private _ContactNumber As String 
    Public Property ContactNumber() As String 
     Get 
      Return _ContactNumber 
     End Get 
     Set(ByVal value As String) 
      _ContactNumber = value 
     End Set 
    End Property 


End Class 

Quiero recorrer las propiedades de la clase anterior. por ejemplo;

Public Sub DisplayAll(ByVal Someobject As Foo) 
    For Each _Property As something In Someobject.Properties 
     Console.WriteLine(_Property.Name & "=" & _Property.value) 
    Next 
End Sub 

Respuesta

264

Uso Reflexión:

Type type = obj.GetType(); 
PropertyInfo[] properties = type.GetProperties(); 

foreach (PropertyInfo property in properties) 
{ 
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null)); 
} 

Editar: También puede especificar un valor BindingFlags a type.GetProperties():

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; 
PropertyInfo[] properties = type.GetProperties(flags); 

que restringirá las propiedades devueltas a propiedades de instancias públicas (excluidas las propiedades estáticas , propiedades protegidas, etc.).

No necesita especificar BindingFlags.GetProperty, lo utiliza al llamar al type.InvokeMember() para obtener el valor de una propiedad.

+0

Por cierto, ¿no debería haber algunos indicadores vinculantes para ese método GetProperties? Me gusta 'BindingFlags.Public | BindingFlags.GetProperty' o algo así? – Svish

+0

@Svish, tienes razón :) Podría usar algunos BindingFlags, pero son opcionales. Probablemente quieras Public | Ejemplo. – Brannon

+0

Consejo: Si se trata de campos estáticos, simplemente pase null aquí: property.GetValue (null); – Seva

28

versión VB de C# dada por Brannon:

Public Sub DisplayAll(ByVal Someobject As Foo) 
    Dim _type As Type = Someobject.GetType() 
    Dim properties() As PropertyInfo = _type.GetProperties() 'line 3 
    For Each _property As PropertyInfo In properties 
     Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing)) 
    Next 
End Sub 

El uso de banderas de unión en vez de la línea no.3

Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance 
    Dim properties() As PropertyInfo = _type.GetProperties(flags) 
+0

Gracias, me hubiera llevado demasiado tiempo convertir a VB :) – Brannon

+0

siempre se puede usar un convertidor automático, hay muchos en la web :) – balexandre

+1

Sí, pero no todos tan buenos como la codificación manual. Uno notable es el convertidor de código telerik –

38

Tenga en cuenta que si el objeto que está hablando tiene un modelo de propiedad personalizada (como DataRowView etc. para DataTable), entonces necesita usar TypeDescriptor; la buena noticia es que esto todavía funciona bien para las clases regulares (e incluso puede ser much quicker than reflection):

foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) { 
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj)); 
} 

Esto también proporciona un fácil acceso a cosas como TypeConverter para el formato:

string fmt = prop.Converter.ConvertToString(prop.GetValue(obj)); 
6

La reflexión es bastante " pesado"

quizás prueba esta solución: // C#

if (item is IEnumerable) { 
    foreach (object o in item as IEnumerable) { 
      //do function 
    } 
} else { 
    foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())  { 
     if (p.CanRead) { 
      Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function 
     } 
    } 
} 

'VB.Net

If TypeOf item Is IEnumerable Then 

    For Each o As Object In TryCast(item, IEnumerable) 
       'Do Function 
    Next 
    Else 
    For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties() 
     If p.CanRead Then 
       Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing)) 'possible function 
      End If 
     Next 
    End If 

Reflexión ralentiza +/- 1,000 x la velocidad de una llamada a un método, mostrado en la The Performance of Everyday Things

1
private void ResetAllProperties() 
    { 
     Type type = this.GetType(); 
     PropertyInfo[] properties = (from c in type.GetProperties() 
            where c.Name.StartsWith("Doc") 
            select c).ToArray(); 
     foreach (PropertyInfo item in properties) 
     { 
      if (item.PropertyType.FullName == "System.String") 
       item.SetValue(this, "", null); 
     } 
    } 

utilicé el bloque de código anterior para restablecer todas las propiedades de cadena en mi objeto de control de usuario web cuyos nombres se inician con "Doc".

0

Ésta es otra manera de hacerlo, utilizando una lambda LINQ:

C#:

SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}")); 

VB.NET:

SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}")) 
1

Esta es la forma en que lo hago.

foreach (var fi in typeof(CustomRoles).GetFields()) 
{ 
    var propertyName = fi.Name; 
} 
Cuestiones relacionadas