如果我有一個帶有嵌套模型的模型。如何根據 NotificationModel 設定 name 屬性并回傳基于嵌套模型中的屬性的串列?
我假設使用 Linq 和 Reflection。
所以我有類似的東西:(假設警報已初始化以及它們是否從資料庫中啟用)。
public class AlarmController : IAlarmController
{
public AlarmController()
{
this.NotificationModel = new NotificationModel();
}
public NotificationModel NotificationModel { get; set; }
public List<AlarmModel> GetAlarmModels()
{
//this.NotificationModel --something... where isEnabled == true.
return new List<AlarmModel>();
}
}
public class NotificationModel
{
public AlarmModel HardwareFault{ get; set; }
public AlarmModel TimeoutFault { get; set; }
public AlarmModel GenericFault { get; set; }
}
public class AlarmModel
{
public string Name { get; set; }
public bool isActive { get; set; }
public bool isEnabled { get; set; }
public bool isSilenced { get; set; }
}
我在反思方面進行了一些嘗試,但還沒有找到像我這樣的例子。我還沒有發布,因為我認為它會混淆問題。如果這不是正確的方法,那么請說出來。
uj5u.com熱心網友回復:
如果我正確理解您的要求,您希望NotificationModel在GetAlarmModels. 然后您可以使用以下方法:
public List<AlarmModel> GetAlarmModels() => EnabledAlarms().ToList();
private IEnumerable<AlarmModel> EnabledAlarms()
{
if(NotificationModel.HardwareFault.isEnabled)
yield return NotificationModel.HardwareFault;
if(NotificationModel.TimeoutFault.isEnabled)
yield return NotificationModel.TimeoutFault;
if(NotificationModel.GenericFault.isEnabled)
yield return NotificationModel.GenericFault;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/363370.html
