簡體   English   中英

如何做到這一點,使我的字段只設置一​​次?

[英]How can I make it so my field is only set the one time?

我的模型類中有一個字段,其編碼如下:

    public string CreatedBy
    {
        get { return _CreatedBy; }
        set { _CreatedBy = value; Created = DateTime.Now; }
    }
    public DateTime? Created { get; set; }

填充CreatedBy字段后,它將自動填寫創建日期。 對我來說,問題是,如果我再次設置CreatedBy字段(是的,可能會發生),那么日期將再次使用當前日期進行更新。

有沒有一種方法可以使CreatedBy和Created字段僅填充一次?

您不能在集合中檢查是否已經存在一個值,而根本不設置新值?

利用構造函數並初始化屬性以實現所需的值

public classConstructor()
{
   propertyName = defaultValue;
}

使用備用字段並檢查該值是否已經設置-如果已設置,請保持不變:

private DateTime? created;
public DateTime? Created 
{
    get { return created; }
    set { if (created == null) created = value; }
}

這是一種快速的方法:使用?? 操作員。 如果Created為null,它將轉到DateTime.Now。

public string CreatedBy
{
    get { return _CreatedBy; }
    set { _CreatedBy = value; Created = Created ?? DateTime.Now; }
}
public DateTime? Created { get; set; }

在這種情況下,最好在構造函數中包含CreatedBy 這意味着“創建時”語義:

public string CreatedBy
{
    get;
    private set;
}

public DateTime? Created
{
    get;
    private set;
}

public Model(..., string createdBy)
{
    this.CreatedBy = createdBy;
    this.Created = DateTime.Now;
}

// another option, if you don't like the ctor route
public void AssignCreator(string createdBy)
{
    if (this.Created.HasValue) throw new InvalidOperationException();
    this.CreatedBy = createdBy;
    this.Created = DateTime.Now;
}

如果Created為非null,則另一個選擇是在屬性設置器中引發InvalidOperationException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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