简体   繁体   中英

Why can't I call a DateTime method on a DateTime object in another class in C#

Ive found a few examples of this problem in other languages such as ruby or php and they seem to indicate that I would need to have some sort of include to support this but I can't exactly figure it out.

I have:

private void setLoansView(Member _member)
{

    foreach (Loan loan in _member.Loans)
        {
            this.dt.Rows.Add(_member.Name, // dt is a datatable 
                   loan.BookOnLoan.CopyOf.Title, 
                   loan.TimeOfLoan.ToShortDateString(), 
                   loan.DueDate.ToShortDateString(), 
                   loan.TimeReturned.ToShortDateString());
        }

Loan looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace Library.Entities
{
    public class Loan
    {
        [Key]
        public int LoanId { get; set; }
        [Required]
        public DateTime? TimeOfLoan { get; set; }
        public DateTime? DueDate { get; set; }
        public DateTime? TimeReturned { get; set; }
        [Required]
        public Copy BookOnLoan { get; set; }
        [Required]
        public Member Loanee { get; set; }
    }
}

On all my DateTime objects in the setLoansView() method I get 'does not contain definition for "ToShortString()". The Member class has an ICollection<Loan> and thats where Im retrieving the loans from. I can't figure out why I loose access to DateTime's methods when I access them from the ICollection though.

That's because the type of these properties is not DateTime , but Nullable<DateTime> . Nullable<T> does not expose such a method.

If you are sure that these dates will have a value, interpose .Value before .ToShortDateString() . If not, you have to decide what should happen in that case.

You have nullable DateTime objects. You'll need to call .Value to get the value (if there is one)

loan.TimeOfLoan.Value.ToShortDateString()

它可以为null,使用.Value获取这些属性(首先检查是否为null)

Because your fields are defined as nullable DateTime?

Just use .Value to access the field's value and you should have your normal DateTime format methods.

Also you should check against null by calling .HasValue

您有一个可为空的DateTime(DateTime?),只有DateTime类具有“ ToShortDateString()”方法...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM