[英]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. Ive在其他语言(如ruby或php)中找到了一些有关此问题的示例,它们似乎表明我需要某种包含来支持此问题,但我无法完全弄清楚。
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()". 在
setLoansView()
方法中所有的DateTime对象上,我得到的不包含“ ToShortString()”的定义。 The Member class has an ICollection<Loan>
and thats where Im retrieving the loans from. Member类具有
ICollection<Loan>
,这就是我从中检索贷款的地方。 I can't figure out why I loose access to DateTime's methods when I access them from the ICollection
though. 但是,当我从
ICollection
访问它们时,我无法弄清楚为什么我松开对DateTime方法的访问。
That's because the type of these properties is not DateTime
, but Nullable<DateTime>
. 这是因为这些属性的类型不是
DateTime
,而是Nullable<DateTime>
。 Nullable<T>
does not expose such a method. Nullable<T>
不公开这种方法。
If you are sure that these dates will have a value, interpose .Value
before .ToShortDateString()
. 如果你确信这些日期将有一个值,介于
.Value
前.ToShortDateString()
If not, you have to decide what should happen in that case. 如果没有,您必须决定在这种情况下应该发生什么。
You have nullable
DateTime
objects. 您有
nullable
DateTime
对象。 You'll need to call .Value
to get the value (if there is one) 您需要调用
.Value
以获取值(如果有的话)
loan.TimeOfLoan.Value.ToShortDateString()
它可以为null,使用.Value
获取这些属性(首先检查是否为null)
Because your fields are defined as nullable DateTime?
因为您的字段被定义为可为null的
DateTime?
Just use .Value
to access the field's value and you should have your normal DateTime format methods. 只需使用
.Value
来访问字段的值,就应该使用常规的DateTime格式方法。
Also you should check against null by calling .HasValue 另外,您还应该通过调用.HasValue来检查是否为null
您有一个可为空的DateTime(DateTime?),只有DateTime类具有“ ToShortDateString()”方法...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.