C#向属性添加逻辑

时间:2020-02-12 12:39:29

标签: c# .net properties

我有一个具有两个属性的模型:

public class AlertRequest
{
   public DateTime? FromDate { get; set; }
   public DateTime? ToDate { get; set; }
}

我需要添加支票这些道具

  • FromDate:当null然后设置为Datetime.MinValue时;
  • ToDate:当null然后设置为Datetime.MaxValue时;

如何在C#中实现呢?

1 个答案:

答案 0 :(得分:3)

您可以手动实现属性

public class AlertRequest
{
   private DateTime? m_FromDate = DateTime.MinValue;
   private DateTime? m_ToDate = DateTime.MaxValue;

   public DateTime? FromDate { 
     get {
       return m_FromDate;
     }
     set {
       m_FromDate = value ?? DateTime.MinValue;
     } 
   }

   public DateTime? ToDate { 
     get {
       return m_ToDate;
     }
     set {
       m_ToDate = value ?? DateTime.MaxValue;
     } 
   }
}

现在我们可以放

AlertRequest request = new AlertRequest();

request.ToDate = null;

// 9999-12-31 (Max Date)
Console.Write(request.ToDate.ToString("yyyy-MM-dd"));