如何在WinRT中获取类的属性

我正在用C#和XAML编写Windows 8应用程序。 我有一个类,它具有许多相同类型的属性,它们在构造函数中以相同的方式设置。 我没有亲自为每个属性编写和赋值,而是希望获得我class级中某些类型的所有属性的列表,并将它们全部设置为foreach。

在“普通”.NET中我会写这个

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

其中j是我的构造函数的参数。 在WinRT中, GetProperties()不存在。 Intellisense for this.GetType(). 没有显示我可以使用的任何有用的东西。

您需要使用GetRuntimeProperties而不是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)) property.SetValue(this, j.GetTuple(property.Name)); } 

试试这个:

 public static IEnumerable GetAllProperties(this TypeInfo type) { var list = type.DeclaredProperties.ToList(); var subtype = type.BaseType; if (subtype != null) list.AddRange(subtype.GetTypeInfo().GetAllProperties()); return list.ToArray(); } 

并像这样使用它:

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

更新:仅当GetRuntimeProperties不可用时才使用此扩展方法,因为GetRuntimeProperties执行相同但是内置方法。