问题描述
我遇到了这个错误
错误源来自此代码
internal class Record
{
[Name("Name")]
public string Name { get; set; }
[Name("Principal")]
public int Principal { get { return Math.Abs(Principal); } set {; } }
}
我搜索了错误,并指出由于 recursive
而导致错误发生.我认为我的 Principal
方法不是递归方法.
I searched the error and it state the error occur because of recursive
. I think my Principal
method is not recursive method.
推荐答案
也许您想考虑以下其中一项:
Perhaps you want to consider one of these:
internal class Record
{
[Name("Name")]
public string Name { get; set; }
[Name("Principal")]
public int Principal { get; set; }
[Name("AbsPrincipal")]
public int AbsPrincipal { get { return Math.Abs(Principal); } set; }
}
internal class Record
{
[Name("Name")]
public string Name { get; set; }
[Name("Principal")]
private int _principal = 0;
public int Principal {
get => _principal;
set => _principal = Math.Abs(value);
}
}
任何返回获得自己的值而没有停止的结果的属性或方法,都会使堆栈溢出.正常工作的递归事物通常具有某种条件,该条件最终会改变状态并停止递归(不会返回获得自己的值的结果)
Any property or method that returns the result of getting its own value with nothing to stop it will overflow the stack. Recursive things that at work correctly usually have something with a condition that eventually changes state and stops the recursion (doesn't return the result of getting its own value)
看看第一个:我们不使属性math.abs本身,我们使它不吸收其他东西-这不能递归,除非其他东西要返回第一个东西(然后递归会失败他们之间)
Take a look at the first one: we don't make the property math.abs itself, we make it abs something else - this cannot recurse unless the something else were to return the first thing (then the recursion would flip flop between them)
第二个可能更像您要执行的操作-再次吸收其他内容(后备变量),而不是属性本身防止递归溢出.在这个集合中,我会abs,因为看来您根本不想检索本金的非Abs值,因此我们最好在存储它时也将其吸收,然后我们就可以检索它一百万次而每次都不吸收.如果您需要对非Abs'd变量的私有访问,则应该在get上执行abs.或者,如果您知道用例将存储一百万次并且仅获取一次,则再次执行abs获得而不是集合.在大多数情况下,我期望的典型程序行为是设置的次数少于获得的次数,因此,我们可以通过谨慎选择何时进行Abs来避免不必要的工作
The second one is probably more like what you want to do- again we abs something else (a backing variable) rather than the property itself preventing recursive overflow. In this one I abs on the set because it seems you never wanted to retrieve the non Abs value for principal so we might as well abs it when we store it then we can just retrieve it a million times without abs each time.. of course if you ever need private access to the non Abs'd variable you should do the abs on the get.. or if you know your use case will be that to store it a million times and only get it once, again do the abs on the get rather than the set. The typical program behavior I would expect in most cases is to set fewer times than get so we can avoid unnecessary work by choosing carefully when to do the abs
这篇关于堆栈溢出异常C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!