簡體   English   中英

為什么我不能在C#中另一個類的DateTime對象上調用DateTime方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM