简体   繁体   English

使readonly属性可设置

[英]Making readonly properties settable

So basically I've come across some readonly properties on this one class that the writer of the class told me I could make settable for a specific task. 所以基本上我在这一课上遇到了一些readonly属性,班级作者告诉我,我可以为特定任务设置可设置。 Problem is, they get their value through manipulation most of the time, not directly from a private variable in the class. 问题是,它们在大多数时间通过操纵获得它们的价值,而不是直接来自类中的私有变量。

Example: 例:

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

So if I want to add a setter, I don't want to worry about setting that Result object because I'm not sure if on it's way back out it's going to be drawn correctly. 因此,如果我想添加一个setter,我不想担心设置Result对象,因为我不确定它是否会退出它将被正确绘制。

Would I be able to do something like this? 我可以做这样的事情吗?

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

Or do any of you see issues that could arise from this (besides the fact that it's now changeable)? 或者你们中的任何人都会看到可能产生的问题(除了它现在可以改变的事实)?

Well your only problem with this is if they set the value to be null and you want your property to return null rather than evaluate the if statement. 那么你唯一的问题是如果他们将值设置为null并且你希望你的属性返回null而不是评估if语句。

But you might not allow them to set null, in which case you should add a check in the setter. 但是你可能不允许它们设置null,在这种情况下你应该在setter中添加一个检查。

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

If it is valid for them to set null, you probably need another boolean flag to tell if the value has been set. 如果它们设置为null有效,则可能需要另一个布尔标志来判断该值是否已设置。

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

我不知道它应该如何工作,但从语法上来说,我没有看到你的代码有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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