如何最好地处理相互依赖的属性?
也许属性不是解决这个问题的方法,但我正在努力寻找一个好的解决方案的答案。
public class Blah
{
public double A { get{ return _B / _C; } }
public double B
{
get{ return _A * _C; }
set{ _B = value; }
}
public double C
{
get{ return _B / _A; }
set{ _C = value; }
}
private double _A;
private double _B;
private double _C;
public Blah(){}
public Blah(double a, double b, double c)
{
this._A = a;
this._B = b;
this._C = c;
}
}
假设 A 始终是只读属性,那么处理可能影响 A 输出的任意数量的附加属性的好方法是什么?我觉得这是一种糟糕的(完全错误的!)方法,因为我应该始终能够检索我分配的值。例如,如果我分配 B = 3,那么下次调用 B 时应该能够得到 3,而不是得到 _A * _C。
但是,我需要存在这种类型的相互依赖(或者实现相同目标的完全不同的方法)。所有值都是相关的,因此我需要将一个值的更改反映在其他值中。
我只是想不出合适的方法来做到这一点。
编辑
我做了一个坏例子。实际上,非 A 值并不依赖于 A,而只是相互依赖——B 影响 C,C 影响 D,等等;然而,A 只是这些值的某种组合。不确定这对于如何最好地解决这个问题是否重要,但认为值得一提。
Perhaps properties aren't the way to go with this, but I'm struggling to find an answer as for a good solution.
public class Blah
{
public double A { get{ return _B / _C; } }
public double B
{
get{ return _A * _C; }
set{ _B = value; }
}
public double C
{
get{ return _B / _A; }
set{ _C = value; }
}
private double _A;
private double _B;
private double _C;
public Blah(){}
public Blah(double a, double b, double c)
{
this._A = a;
this._B = b;
this._C = c;
}
}
Assuming A is always a read-only property, what's a good way to go about handling an arbitrary amount of additional properties that may affect the output of A? I feel this is a bad (completely wrong!) way to do this because I should always be able to retrieve a value I assign. For example, if I assign B = 3, then I should be able to get 3 the next time I call B instead of getting _A * _C.
However, I need for this type of interdependence to exist (or a completely different approach that achieves the same goal). All of the values are related, so I need for the change of one value to be reflected in the others.
I just can't figure out the appropriate way to do this.
Edit
I made a bad example. In reality, the non-A values aren't dependent on A, but only each other -- B affects C, C affects D, etc; however, A is just some combination of those values. Not sure if that matters as for how to best approach this, but thought it was worth mentioning.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来将其称为属性 A 并不能很好地描述它。如果您有一个名为
SolveForA()
的方法,那么它会更有意义。其他人也一样。使用 WriteOnly 属性仍然可能有意义,但我也会使用这些方法。It seems that calling it property A doesn't really describe it well. If you had a method that was called
SolveForA()
, it would make a lot more sense. Same for the others. Using WriteOnly properties still might make sense, but I'd make those methods as well.在我看来,在所提供的示例中,属性被滥用了。您已经注意到,我们可以预期,如果我们设置值,我们也将能够获得相同的值。如果重构代码是我的工作,我想我想从以下开始:
In my opinion in presented example properties are misused. You already noticed that we can expect that if we will set value, we will be able also to get the same value. If refactoring of the code would be my job, I think I would like to start from something like: