2012-11-02 13 views
13

Sto scrivendo un'applicazione Windows 8 in C# e XAML. Ho una classe con molte proprietà dello stesso tipo che sono impostate nel costruttore nello stesso modo. Invece di scrivere e assegnare per ciascuna delle proprietà a mano, voglio ottenere un elenco di tutte le proprietà di un determinato tipo sulla mia classe e impostarle tutte in un foreach.Come ottenere le proprietà di una classe in WinRT

In .NET "normale" Vorrei scrivere questo

var properties = this.GetType().GetProperties(); 
foreach (var property in properties) 
{ 
    if (property.PropertyType == typeof(Tuple<string,string>)) 
    property.SetValue(this, j.GetTuple(property.Name)); 
} 

dove j è un parametro del mio costruttore. In WinRT il GetProperties() non esiste. Intellisense per this.GetType(). non mostra nulla di utile che potrei usare.

+2

http://msdn.microsoft.com/en-us/library/windows/apps/br230302.aspx#reflection –

risposta

16

è necessario utilizzare GetRuntimeProperties invece di GetProperties:

var properties = this.GetType().GetRuntimeProperties(); 
// or, if you want only the properties declared in this class: 
// var properties = this.GetType().GetTypeInfo().DeclaredProperties; 
foreach (var property in properties) 
{ 
    if (property.PropertyType == typeof(Tuple<string,string>)) 
    property.SetValue(this, j.GetTuple(property.Name)); 
} 
+2

Errore: "System.Type" non contiene una definizione per "GetTypeInfo" –

+3

È un metodo di estensione , è necessario importare lo spazio dei nomi 'System.Reflection' –

+0

Dopo aver importato' System.Reflection', ho ottenuto che 'System.Reflection.TypeInfo' non contenga una definizione per 'GetProperties'. Sono necessarie altre importazioni? –

6

Prova questo:

public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo type) 
{ 
    var list = type.DeclaredProperties.ToList(); 

    var subtype = type.BaseType; 
    if (subtype != null) 
     list.AddRange(subtype.GetTypeInfo().GetAllProperties()); 

    return list.ToArray(); 
} 

e usarlo in questo modo:

var props = obj.GetType().GetTypeInfo().GetAllProperties(); 

Aggiornamento: utilizzare questa estensione metodo solo se GetRuntimeProperties non è disponibile perché GetRuntimeProperties fa lo stesso, ma è un metodo integrato.

+0

Spero davvero che questa funzione possa essere aggiunta alla classe 'TypeInfo' stessa. – hardywang

Problemi correlati