2009-02-10 23 views
146

Ho una lezione.Come eseguire il ciclo di tutte le proprietà di una classe?

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 

Voglio passare in rassegna le proprietà della classe precedente. es .;

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

risposta

264

utilizzare la riflessione:

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

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

Modifica: È inoltre possibile specificare un valore BindingFlags a type.GetProperties():

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

che limiterà le proprietà restituite alle proprietà delle istanze pubbliche (escluse le proprietà statiche , proprietà protette, ecc.).

Non è necessario specificare BindingFlags.GetProperty, lo si utilizza quando si chiama type.InvokeMember() per ottenere il valore di una proprietà.

+0

Btw, non dovrebbero esserci alcuni flag di associazione per quel metodo GetProperties? Mi piace "BindingFlags.Public | BindingFlags.GetProperty' o qualcosa del genere? – Svish

+0

@Svish, hai ragione :) Potrebbe utilizzare alcuni BindingFlags, ma sono facoltativi. Probabilmente vuoi Public | Esempio. – Brannon

+0

Suggerimento: se hai a che fare con campi statici, passa semplicemente null qui: property.GetValue (null); – Seva

28

versione VB di C# data dal 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 

Utilizzando bandiere obbligatorio in tutti invece di linea n ° 3

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

Grazie, mi ci sarebbe voluto troppo tempo per convertire in VB :) – Brannon

+0

è sempre possibile utilizzare un convertitore automatico, ce ne sono tantissimi nel web :) – balexandre

+1

Sì ma non tutto è buono come la codifica manuale. Uno dei più importanti è il convertitore di codice telerik –

38

Nota che se l'oggetto che si sta parlando ha un modello di proprietà personalizzata (come DataRowView ecc. per DataTable), quindi è necessario utilizzare TypeDescriptor; la buona notizia è che questo funziona ancora bene per le classi regolari (e può anche essere much quicker than reflection):

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

Questo fornisce anche un facile accesso a cose come TypeConverter per la formattazione:

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

riflessione è abbastanza " pesante"

magari provare questa soluzione: // 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 

Riflessione rallenta +/- 1000 x la velocità di una chiamata di metodo, illustrato nella 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); 
     } 
    } 

ho usato il codice di blocco sopra per reimpostare tutte le proprietà di stringa nel mio oggetto di controllo utente web, quali nomi iniziano con "Doc".

0

Ecco un altro modo per farlo, utilizzando un 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

Questo è come lo faccio.

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