Nullable DateTime?

后端 未结 6 513
刺人心
刺人心 2021-01-11 14:17

how to create setter and getter Properties for nullable datetime. for example:

private DateTime mTimeStamp;

public DateTime TimeStamp
{
      get { return m         


        
相关标签:
6条回答
  • 2021-01-11 14:24
    private DateTime? mTimeStamp;
    
    public DateTime? TimeStamp
    {
      get { return mTimeStamp; }
      set { mTimeStamp = value; }
    }
    

    or, if you are using .net 3.0+

    public DateTime? TimeStamp {get;set;}
    
    0 讨论(0)
  • 2021-01-11 14:27

    You should be able to make a DateTime nullable in this way:

    private DateTime? mTimeStamp;
    
    public DateTime? TimeStamp
    {
          get { return mTimeStamp; }
          set { mTimeStamp = value; }
    }
    

    You can use this modifier on other types as well. Read up here: http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=VS.100%29.aspx

    0 讨论(0)
  • 2021-01-11 14:34

    A nullable DateTime is a discrete type from a regular DateTime and can be used like any other type. So your code would be:

    private DateTime? mTimeStamp;
    
    public DateTime? TimeStamp
    {
          get { return mTimeStamp; }
          set { mTimeStamp = value; }
    }
    
    0 讨论(0)
  • 2021-01-11 14:39

    It's the same as non-nullable:

    public DateTime? TimeStamp { get; set; }

    You can replace DateTime with DateTime? in your top sample code (looks like code is missing at the bottom of your post).

    0 讨论(0)
  • 2021-01-11 14:42

    You can just do this instead:

    public DateTime? TimeStamp { get; set; }
    

    If you were having trouble with the compiler it's probably because you only changed one of the associated parts - either the private member variable or the property's data type. They need to match, of course, and auto-properties handles that for you nicely.

    EDIT Just to further clarify, DateTime? is not merely decorated with an ? attribute - it's entirely different from DateTime. DateTime? is shorthand for Nullable<DateTime>, which is a generic (Nullable<T>) that provides nullable support to non-reference types by wrapping the generic parameter T, which is a struct.

    0 讨论(0)
  • 2021-01-11 14:48

    You can create the property in the same way as a normal DateTime property:

    public DateTime? TimeStamp { get; set; }
    
    0 讨论(0)
提交回复
热议问题