简体   繁体   English

C#可空与不可空DateTime标签

[英]C# Nullable vs Non-Nullable DateTime tags

This is an EPIC story about date and time. 这是一个有关日期和时间的EPIC故事。

Created is a non-nullable DateTimeOffset variable Updated is a nullable DateTimeOffset variable 创建的是一个不可为空的DateTimeOffset变量更新的是一个可为空的DateTimeOffset变量

Values of both have been created properly, exist in the DB and have been passed to the view. 两者的值均已正确创建,存在于数据库中并已传递到视图。 So both of these values should be available within: <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> 因此,这两个值都应该在以下范围内可用: <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>

However the second (Updated) is good-to-go and the first(Created) pulls an error: "ValueExtensions.Value(HtmlHelper, string)' is a method, which is not valid in the given context" 但是,第二个(Updated)很好,第一个(Created)产生了错误:“ ValueExtensions.Value(HtmlHelper,string)'是一种方法,在给定的上下文中无效”

It occurs on the .value part. 它发生在.value部分。 Why is one ok and the other not? 为什么一个可以,另一个不可以呢? What would the nullability of the variable have to do with it being acceptable? 变量的可空性与可接受性有什么关系? or make the method 'not valid in the given context'? 或使方法“在给定的上下文中无效”?

My Model: 我的模特:

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

Nullable type values can be accessed with .Value . 可以使用.Value访问可空类型值。

Non-nullable types do not have .Value . 非可空类型没有.Value

Since Model.Created is not Nullable, you would access it's value simply by calling Model.Created . 由于Model.Created不可为空,因此只需调用Model.Created即可访问其值。

Read up on the Nullable Structures here . 这里阅读可空结构。

You have two typo's. 你有两个错字。 Firstly the extra > on the between div and class, secondly non-nullable objects don't have a Value property. 首先,div和class之间的extra>,其次非空对象没有Value属性。

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM