为什么我不能在C#中的另一个类的DateTime对象上调用DateTime方法

时间:2013-11-18 16:16:03

标签: c# datetime icollection

我已经在其他语言中找到了一些这个问题的例子,例如ruby或php,它们似乎表明我需要某种包含来支持这一点,但我无法弄明白这一点。

我有:

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

贷款看起来像这样:

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

在我得到的setLoansView()方法中的所有DateTime对象中,不包含“ToShortString()”的定义。会员类有一个ICollection<Loan>,那就是我从中检索贷款的地方。我无法弄清楚为什么当我从ICollection访问它时,我无法访问DateTime的方法。

5 个答案:

答案 0 :(得分:6)

这是因为这些属性的类型不是DateTime,而是Nullable<DateTime>Nullable<T>没有公开这样的方法。

如果您确定这些日期 会有值,请在.Value之前插入.ToShortDateString()。如果没有,你必须决定在这种情况下会发生什么。

答案 1 :(得分:1)

您拥有nullable DateTime个对象。您需要致电.Value以获取值(如果有的话)

loan.TimeOfLoan.Value.ToShortDateString()

答案 2 :(得分:1)

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

答案 3 :(得分:1)

因为您的字段被定义为可为空DateTime?

只需使用.Value访问字段的值,您应该使用正常的DateTime格式方法。

此外,您应该通过调用.HasValue

来检查null

答案 4 :(得分:0)

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