2011-11-22 196 views
1

我在如下编码真实我的模型类中的字段:我怎样才能让我的领域只设置一次?

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

当CreatedBy字段被填充那么它会自动填写创建日期。我的问题是,如果我再次设置CreatedBy字段(是的,它可能会发生),那么日期会再次更新当前日期。

有没有一种方法可以使CreatedBy和Created字段只填充一次?

+0

曾经由谁填充过?这是坚持在数据库? –

回答

1

使用支持字段,并检查该值是否已经设置 - 如果是这样,离开它不变:

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

。利用构造和iniailize到defult值的属性你想

public classConstructor() 
{ 
    propertyName = defaultValue; 
} 
2

你能不能查,该组中,是否已经有一个值,根本就没有设置新的价值?

+0

+1。您将逻辑编程到set方法中。 – TomTom

1

下面是一个简单的方法:用?运营商。如果Created为null,则它将转到DateTime.Now。

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

+1回答这个问题,而不告诉OP在构造函数中设置值(这可能是也可能不是一个好建议) –

+0

@KirkBroadhurst好吧,在构造函数中设置它肯定会成为答案。这将是*期望的用例(设置一次,忘记它),而不是让一些属性的集合具有设置另一个属性的副作用,尽管这通常是不好的设计,但可能是这里所期望的效果。 – MPelletier

+0

但是你不能在构造函数中设置每个属性!任何名为'Created ...'的属性都会在构造函数中设置* sound *,但我从不假设这些东西。 –

1

在这种情况下,最好在构造函数中包含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为非空。