2011-11-16 151 views
4

所以基本上我已经遇到了这个类的一些readonly属性,该类的作者告诉我,我可以为特定任务进行设置。问题在于,他们大多数时间都是通过操纵获得价值,而不是直接从班级中的私人变量中获取价值。使只读属性可设置

例子:

public decimal? AccruedInterest 
{ 
    get 
    { 
     if (this.Result != null) 
     { 
      return this.GetExchangedCurrencyValue(this.Result.AccruedInterest.GetValueOrDefault(decimal.Zero)); 
     } 
     return null; 
    } 
} 

所以,如果我想添加一个二传手,我不想担心设置该Result对象,因为我不知道,如果它的方式回到了它的将是正确绘制。

我能做这样的事吗?

private decimal? _AccruedInterest; 
public decimal? AccruedInterest 
{ 
    get 
    { 
     if (this._AccruedInterest.HasValue) 
     { 
      return this._AccruedInterest.Value; 
     } 
     if (this.Result != null) 
     { 
      return this.GetExchangedCurrencyValue(this.Result.AccruedInterest.GetValueOrDefault(decimal.Zero)); 
     } 
     return null; 
    } 
    set 
    { 
     this._AccruedInterest = value; 
    } 
} 

或者你们有没有看到可能由此产生的问题(除了现在可以改变的事实)?

+1

你的问题到底是什么?你应该问这个人他们决定制造这些房产的原因,然后迅速地将他们打包,因为暗示你有一些破解来改变他们的价值。 –

回答

3

那么你唯一的问题是,如果他们将值设置为null,并且你希望你的属性返回null而不是评估if语句。

但是你可能不允许他们设置null,在这种情况下你应该在setter中添加一个检查。

set 
{ 
    if (value == null) 
     throw new NullArgumentException("AccruedInterest"); 
    this._AccruedInterest = value; 
} 

如果它是有效的为他们设置为空,你可能需要另一个布尔标志,告诉如果该值已设置。

private bool _accruedInterestSet; 
private decimal? _accruedInterest; 
public decimal? AccruedInterest 
{ 
    get 
    { 
     if (this._accruedInterestSet) 
     { 
      return this._accruedInterest; //don't return .Value in case they set null 
     } 
     if (this.Result != null) 
     { 
      return this.GetExchangedCurrencyValue(this.Result.AccruedInterest.GetValueOrDefault(decimal.Zero)) ; 
     } 
     return null; 
    } 
    set 
    { 
     this._accruedInterestSet = true; 
     this._AccruedInterest = value; 
    } 
} 
+0

AFAIK在这种情况下'this._AccruedInterest.HasValue'返回'false' – NaveenBhat

+0

这应该没有必要。如果'_AccruedInterest'为空,'HasValue'将评估为false。 –

+0

@Knvn是的,这就是我要说的。如果允许用户设置null,并且您希望该属性在该情况下返回null(而不是其他代码),则需要进行不同的检查。 – Ray

0

我不知道它是如何工作的,但在语法上我没有看到你的代码有什么问题。