[英]Why can't I call a DateTime method on a DateTime object in another class in C#
Ive在其他语言(如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()”的定义。 Member类具有ICollection<Loan>
,这就是我从中检索贷款的地方。 但是,当我从ICollection
访问它们时,我无法弄清楚为什么我松开对DateTime方法的访问。
这是因为这些属性的类型不是DateTime
,而是Nullable<DateTime>
。 Nullable<T>
不公开这种方法。
如果你确信这些日期将有一个值,介于.Value
前.ToShortDateString()
如果没有,您必须决定在这种情况下应该发生什么。
您有nullable
DateTime
对象。 您需要调用.Value
以获取值(如果有的话)
loan.TimeOfLoan.Value.ToShortDateString()
它可以为null,使用.Value
获取这些属性(首先检查是否为null)
因为您的字段被定义为可为null的DateTime?
只需使用.Value
来访问字段的值,就应该使用常规的DateTime格式方法。
另外,您还应该通过调用.HasValue来检查是否为null
您有一个可为空的DateTime(DateTime?),只有DateTime类具有“ ToShortDateString()”方法...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.