简体   繁体   中英

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

I have a field in my model class that's coded as follows:

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

When the CreatedBy field is populated then it fills out the Created date automatically. The problem for me is that if I again set the CreatedBy field (yes it can happen) then the date gets updated with the current date again.

Is there a way that I can make it so the CreatedBy and the Created fields can be populated just once?

您不能在集合中检查是否已经存在一个值,而根本不设置新值?

Make use of constructor and iniailize the property to defult value you want

public classConstructor()
{
   propertyName = defaultValue;
}

Use a backing field and check whether the value has been set already - if so, leave it unchanged:

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

Here's a quick way: use the ?? operator. If Created is null, it will go to DateTime.Now.

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

In that case it would probably be best to include CreatedBy in the constructor. This would imply "create-time" semantics:

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

Your other option would be to throw an InvalidOperationException in the property setter if Created is non-null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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