【问题标题】:C# Nullable vs Non-Nullable DateTime tagsC# Nullable vs Non-Nullable DateTime 标签
【发布时间】:2016-08-01 03:46:22
【问题描述】:

这是一个关于日期和时间的史诗故事。

Created 是一个不可为空的 DateTimeOffset 变量 Updated 是一个可为空的 DateTimeOffset 变量

两者的值都已正确创建,存在于数据库中并已传递给视图。所以这两个值都应该在:<div class="row">@Html.Label(Model.Created.Value.ToString("MMMM, dd yyyy hh:mm tt"))</div> <div class="row">@Html.Label(Model.Updated.Value.ToString("MMMM, dd yyyy hh:mm tt"))</div>

但是第二个(更新的)是好的,第一个(创建的)会出现错误:“ValueExtensions.Value(HtmlHelper, string)' is a method, which is not valid in the given context"

它发生在 .value 部分。 为什么一个可以,另一个不行?变量的可空性与可接受性有什么关系?还是使该方法“在给定的上下文中无效”?

我的模特:

 public BlogPost()
    {
        this.Comments = new HashSet<Comment>();
    }

    public int Id { get; set; }

    public DateTimeOffset Created { get; set; }
    public DateTimeOffset? Updated { get; set; }

    [Required()]
    public string Title { get; set; }
    public string Slug { get; set; }
    [Required()]
    [AllowHtml]
    public string Body { get; set; }
    public string MediaURL { get; set; }
    public bool Published { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }

【问题讨论】:

    标签: c# datetime nullable datetimeoffset non-nullable


    【解决方案1】:

    可以使用.Value 访问可空类型值。

    不可为空的类型没有.Value

    由于Model.Created 不可为空,您只需调用Model.Created 即可访问它的值。

    阅读可空结构here

    【讨论】:

      【解决方案2】:

      你有两个错字。首先是 div 和 class 之间的额外 >,其次不可为空的对象没有 Value 属性。

      试试这个:

      <div class="row">
        @Html.Label(Model.Created.ToString("MMMM, dd yyyy  hh:mmtt"))
      </div>
      

      【讨论】:

      • 嗯,这两个部分都很好。不知道“>”是怎么进去的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多