【问题标题】:How to get properties of a class in WinRT如何在 WinRT 中获取类的属性
【发布时间】:2012-11-02 14:57:39
【问题描述】:

我正在用 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() 不存在。 this.GetType(). 的 Intellisense 没有显示我可以使用的任何有用的东西。

【问题讨论】:

标签: c# reflection microsoft-metro windows-runtime


【解决方案1】:

您需要使用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));
}

【讨论】:

  • 错误:“System.Type”不包含“GetTypeInfo”的定义
  • 是扩展方法,需要导入System.Reflection命名空间
  • 导入System.Reflection 后,我得到“System.Reflection.TypeInfo”不包含“GetProperties”的定义。还需要其他进口吗?
  • @IgorKulman,抱歉,忘记了...您可以使用GetRuntimeProperties()(获取所有属性,包括继承的属性)或DeclaredProperties(仅获取此类型声明的属性)。查看我的编辑
  • 阅读文档 (msdn.microsoft.com/en-us/library/windows/apps/…) 时,您必须忽略那些没有绿色公文包图标的项目(在 .NET 中支持 Windows Store 应用程序)。
【解决方案2】:

试试这个:

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 的作用相同,但它是一个内置方法。

【讨论】:

  • 我真的希望这个功能可以添加到TypeInfo类本身。
猜你喜欢
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2019-05-20
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 2018-03-19
相关资源
最近更新 更多