gpt4 book ai didi

c# - 简化循环获取类的属性

转载 作者:行者123 更新时间:2023-11-30 13:36:02 24 4
gpt4 key购买 nike

我有这两个 foreach 循环来线性获取我的一个类的所有属性。

foreach (PropertyInfo property in GetType().GetProperties())
{
foreach (Attribute attribute in property.GetCustomAttributes(true))
{
}
}

如何将这两个循环简化为一个循环或 linq 操作以获取类属性?

最佳答案

你可以依赖SelectMany()

var attributes = GetType().GetProperties()
.SelectMany(p => p.GetCustomAttributes(true));

foreach (var attribute in attributes)
{
// Code goes here
}

关于c# - 简化循环获取类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41110373/

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