Igo*_*man 13 c# reflection microsoft-metro windows-runtime
我正在用C#和XAML编写Windows 8应用程序.我有一个类,它具有许多相同类型的属性,这些属性在构造函数中以相同的方式设置.而不是手动编写和分配每个属性我想获得我的类中的某些类型的所有属性的列表,并将它们全部设置为foreach.
在"普通".NET中我会写这个
var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
if (property.PropertyType == typeof(Tuple<string,string>))
property.SetValue(this, j.GetTuple(property.Name));
}
Run Code Online (Sandbox Code Playgroud)
where j是我的构造函数的参数.在WinRT GetProperties()中不存在.Intellisense for this.GetType().没有显示我可以使用的任何有用的东西.
Tho*_*que 16
您需要使用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<string,string>))
property.SetValue(this, j.GetTuple(property.Name));
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
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();
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
var props = obj.GetType().GetTypeInfo().GetAllProperties();
Run Code Online (Sandbox Code Playgroud)
更新:仅当GetRuntimeProperties不可用时才使用此扩展方法,因为GetRuntimeProperties它是相同的但是是内置方法.