2016-10-07 32 views
1

而不是手動設置對象中的每個布爾屬性。我想要使​​用反射爲所有布爾屬性。C#在LINQ語句中使用propertyinfo(反射)

//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

當你已經知道你的類型似乎非常複雜時使用反射。根據您的方法運行的頻率(以及您的代碼對性能的影響程度),還有內存和CPU成本。 http://stackoverflow.com/questions/224232/what-is-the-cost-of-net-reflection –

+0

在未來的變化中,新的動作可能會被添加到模型中。此代碼是表示邏輯的一部分。我希望代碼保持正常工作,這意味着要處理添加的新標誌/布爾值。機會是另一個程序員,(如果不是通過反射來完成的話,將來可能會是我)會忘記更新這個方法。如果性能成爲問題,我將使用T4模板生成此代碼。 –

回答

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; }

那麼這個作品!

這兩個陳述的工作。但哪一個更好?

0

這應該工作(在foreach內):

propInfo.SetValue(result, (from m in afList where (bool)propInfo.GetValue(m) select true).FirstOrDefault())