使用 LINQ 循环访问类属性
本文关键字:属性 访问 循环 LINQ 使用 | 更新日期: 2023-09-27 18:37:15
有一个 ParsedTemplate 类,它有超过 300 个属性(类型化 Details 和 BlockDetails)。parsedTemplate 对象将由函数填充。填充此对象后,我需要 LINQ(或其他方式)来查找是否有任何属性,例如 "body" 或 "img",其中IsExist=false
和Priority="high"
。
public class Details
{
public bool IsExist { get; set; }
public string Priority { get; set; }
}
public class BlockDetails : Details
{
public string Block { get; set; }
}
public class ParsedTemplate
{
public BlockDetails body { get; set; }
public BlockDetails a { get; set; }
public Details img { get; set; }
...
}
你需要编写自己的方法来使它开胃。幸运的是,它不需要很长时间。像这样:
static IEnumerable<Details> GetDetails(ParsedTemplate parsedTemplate)
{
return from p in typeof(ParsedTemplate).GetProperties()
where typeof(Details).IsAssignableFrom(p.PropertyType)
select (Details)p.GetValue(parsedTemplate, null);
}
然后,如果要检查ParsedTemplate
对象上是否存在任何属性,则可以使用 LINQ:
var existingDetails = from d in GetDetails(parsedTemplate)
where d.IsExist
select d;
如果你真的想在这样做时使用linq,你可以尝试这样的事情:
bool isMatching = (from prop in typeof(ParsedTemplate).GetProperties()
where typeof(Details).IsAssignableFrom(prop.PropertyType)
let val = (Details)prop.GetValue(parsedTemplate, null)
where val != null && !val.IsExist && val.Priority == "high"
select val).Any();
在我的机器上工作。
或在扩展方法语法中:
isMatching = typeof(ParsedTemplate).GetProperties()
.Where(prop => typeof(Details).IsAssignableFrom(prop.PropertyType))
.Select(prop => (Details)prop.GetValue(parsedTemplate, null))
.Where(val => val != null && !val.IsExist && val.Priority == "high")
.Any();
使用 c# 反射。例如:
ParsedTemplate obj;
PropertyInfo pi = obj.GetType().GetProperty("img");
Details value = (Details)(pi.GetValue(obj, null));
if(value.IsExist)
{
//Do something
}
我没有编译,但我认为它有效。
ParsedTemplate tpl = null;
// tpl initialization
typeof(ParsedTemplate).GetProperties()
.Where(p => new [] { "name", "img" }.Contains(p.Name))
.Where(p =>
{
Details d = (Details)p.GetValue(tpl, null) as Details;
return d != null && !d.IsExist && d.Priority == "high"
});