有一个 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;
关于c# - 使用 LINQ 迭代类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11033198/