c# - C# 查找符合特定条件的对象的属性
问题描述
假设你有这个类:
// this is c# btw
class Rewards {
public int property1 {get;set;}
public int property2 {get;set;}
public int property3 {get;set;}
}
你在某处创建了该类的一个实例并更新了它的一些值
Rewards reward = new Rewards();
reward.property1 = 10000000000;
现在,您要做的是获取其值与特定条件匹配的属性的名称(例如:值大于 0 的属性 -> 在这种情况下Property1将被返回/推入数组
你会怎么做呢?
我的尝试:
var allRewards = typeof(Rewards).GetProperties().ToList(); // this gets all the properties, but I'm not sure how the filter them with a Where query
Debug.Log(typeof(Rewards).GetProperty(allRewards[1].Name).GetValue(rewards))); // printing one of the values as a test - which works
所以它应该做的是迭代每个属性,运行某个标准,如果它通过测试,则将该属性存储在一个列表中
我明白了,我可以使用 for 循环遍历列表,但我想要一个带有 Where 查询的解决方案
解决方案
您可以通过获取所有属性GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)
并用于Where
将特定属性存储在records
List<PropertyInfo> records = rewards.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)
.Where(a => a.PropertyType == typeof(int) && ((int)a.GetValue(rewards)) > 10000)
.ToList();
foreach (var item in records)
{
Console.WriteLine(item.Name + " " + item.GetValue(rewards));
}
推荐阅读
- amazon-web-services - 使用一个数据库还是多个数据库更好?
- c# - Kestrel下的UDP监听器
- reporting-services - SSRS - 默认用户没有管理员权限
- c# - 使用 C# 使用 PowerShell 获取 AD 组仅返回 256 条记录
- javascript - React-Native SagaTester“在 jest.setTimeout 指定的 5000 毫秒超时内未调用异步回调”
- angular - 在将表单数据传递给角度参数时未定义
- odoo - 在 Odoo14 的报告中添加提醒费
- reactjs - 使用动态路由在 React 中设置每个用户的登录页面
- c# - 无法在 winforms 中将 ValueMember 设置为 listBox
- python - Pandas:如果字符串存在于几列中的任何一列中,我想求和一个计数,并将这个计数添加到另一个带有搜索词的数据框中