而不是手动设置对象中的每个布尔属性。我想使用反射为所有布尔属性执行此操作。
//For each boolean property: if any in collection is true, result is true.
private ActionFlagsViewModel StackActionFlagsViewModels(List<ActionFlagsViewModel> afList)
{
var result = new ActionFlagsViewModel();
foreach (var propInfo in typeof(ActionFlagsViewModel).GetProperties().Where(p => p.PropertyType == typeof(System.Boolean)))
{
// TODO: Do this using reflection for each property info.
result.ShowActionAbort = afList.Where(afvm => afvm.ShowActionAbort == true).Any();
result.ShowActionAssign = afList.Where(afvm => afvm.ShowActionAssign == true).Any();
}
return result;
}
这应该很容易吗?
答案 0 :(得分:0)
这应该有效(在foreach内部):
propInfo.SetValue(result, (from m in afList where (bool)propInfo.GetValue(m) select true).FirstOrDefault())
答案 1 :(得分:0)
public ActionFlagsViewModel StackActionFlagsViewModels(List<ActionFlagsViewModel> afList)
{
var result = new ActionFlagsViewModel();
foreach (var propInfo in typeof(ActionFlagsViewModel).GetProperties().Where(p => p.PropertyType == typeof(System.Boolean)))
{
propInfo.SetValue(result, (from m in afList where (bool)propInfo.GetValue(m) select true).FirstOrDefault());
//propInfo.SetValue(result, afList.Where(afvm => Convert.ToBoolean(propInfo.GetValue(afvm)) == true).Any());
}
return result;
}
这很有效!
这两个陈述都有效。但哪一个更好?