![](/img/trans.png)
[英]initialize an IEnumerable property using reflection in c# (propertyInfo)
[英]C# using propertyinfo ( reflection ) in LINQ statement
而不是手動設置對象中的每個布爾屬性。 我想使用反射為所有布爾屬性執行此操作。
//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;
}
這應該很容易嗎?
這應該工作(在foreach內部):
propInfo.SetValue(result, (from m in afList where (bool)propInfo.GetValue(m) select true).FirstOrDefault())
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;
}
這很有效!
兩個陳述都有效。 但哪一個更好?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.