簡體   English   中英

如何在WinRT中獲取類的屬性

[英]How to get properties of a class in WinRT

我正在用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));
}

其中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<string,string>))
    property.SetValue(this, j.GetTuple(property.Name));
}

嘗試這個:

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

並像這樣使用它:

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

更新:僅當GetRuntimeProperties不可用時才使用此擴展方法,因為GetRuntimeProperties執行相同操作但是是內置方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM