gpt4 book ai didi

c# - 如何在 WinRT 中获取类的属性

转载 作者:可可西里 更新时间:2023-11-01 08:05:32 24 4
gpt4 key购买 nike

我正在使用 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 没有显示任何我可以使用的有用信息。

最佳答案

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

关于c# - 如何在 WinRT 中获取类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com