我怎样才能让我的领域只设置一次?
我在如下编码真实我的模型类中的字段:我怎样才能让我的领域只设置一次?
public string CreatedBy
{
get { return _CreatedBy; }
set { _CreatedBy = value; Created = DateTime.Now; }
}
public DateTime? Created { get; set; }
当CreatedBy字段被填充那么它会自动填写创建日期。我的问题是,如果我再次设置CreatedBy字段(是的,它可能会发生),那么日期会再次更新当前日期。
有没有一种方法可以使CreatedBy和Created字段只填充一次?
使用支持字段,并检查该值是否已经设置 - 如果是这样,离开它不变:
private DateTime? created;
public DateTime? Created
{
get { return created; }
set { if (created == null) created = value; }
}
。利用构造和iniailize到defult值的属性你想
public classConstructor()
{
propertyName = defaultValue;
}
下面是一个简单的方法:用?运营商。如果Created为null,则它将转到DateTime.Now。
public string CreatedBy
{
get { return _CreatedBy; }
set { _CreatedBy = value; Created = Created ?? DateTime.Now; }
}
public DateTime? Created { get; set; }
+1回答这个问题,而不告诉OP在构造函数中设置值(这可能是也可能不是一个好建议) –
@KirkBroadhurst好吧,在构造函数中设置它肯定会成为答案。这将是*期望的用例(设置一次,忘记它),而不是让一些属性的集合具有设置另一个属性的副作用,尽管这通常是不好的设计,但可能是这里所期望的效果。 – MPelletier
但是你不能在构造函数中设置每个属性!任何名为'Created ...'的属性都会在构造函数中设置* sound *,但我从不假设这些东西。 –
在这种情况下,最好在构造函数中包含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;
}
你的另一个选项是在属性setter抛出InvalidOperationException
如果Created
为非空。
曾经由谁填充过?这是坚持在数据库? –