2012-11-02 21 views
13

C# ve XAML'de bir Windows 8 uygulaması yazıyorum. Kurucuda aynı şekilde ayarlanmış aynı türden birçok özelliği olan bir sınıfım var. Her bir özellik için elle yazma ve atama yerine, sınıfımdaki tüm özelliklerin bir listesini almak ve hepsini bir foreach'a yerleştirmek istiyorum. "Normal" NET'teWinRT'de bir sınıfın özelliklerini edinme

ben yazardım bu

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

. WinRT'de GetProperties() mevcut değil. this.GetType(). için Intellisense, kullanabileceğim yararlı bir şey göstermiyor.

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(); 
} 

ve bu gibi kullanmak:

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

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

cevap

16

Sen GetProperties yerine GetRuntimeProperties kullanmak gerekir

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

Güncelleme: kullanın bu uzantı yöntem yalnızcaise 0, GetRuntimeProperties aynı değil, ancak yerleşik bir yöntem olduğundan kullanılabilir değil.

+2

Hata: 'SystemType', 'GetTypeInfo' –

+3

için bir tanım içermiyor Bu bir uzantı yöntemidir , 'System.Reflection' ad alanını –

+0

almanız gerekir.' System.Reflection 'içe aktarıldıktan sonra' System.Reflection.TypeInfo 'ifadesi' GetProperties 'için bir tanım içermiyor. Diğer ithalatlar gerekli mi? –

6

bu deneyin:

+0

Gerçekten bu fonksiyonun 'TypeInfo' sınıfının kendisine eklenebileceğini umuyoruz. – hardywang

İlgili konular