Recursive function in Silverlight
I have the following function in my c# silverlight application to find the total sub nodes of a node in the tree
//get total children
private int getTotalChildren(int id)
{
int total=0;
for (int i = 0; i < persons.Count;i++ )
{
if (persons[i].Manager == id)
{
total += 1;
total += getTotalChildren(persons[i].Id);
}
}
return total;
}
the line total += getTotalChildren(persons[i].id) is making the browser windows auto close when i run it (i am guessing thats silverlights way of crashing?) in the IDE I don't get any errors.
edit: I don't see how it could be infinite recursion since there is no person which has itself as manager. persons is a List built using this xml
<?xml version="1.0" ?>
<Persons>
<Person>
<Id>1</Id>
<Name>temp</Name>
<Qlid>1234</Qlid>
<Manager>0</Manager>
</Person>
<Person>
<Id>2</Id>
<Name>someone</Name>
<Qlid>5678</Qlid>
<Man开发者_C百科ager>1</Manager>
</Person>
<Person>
<Id>3</Id>
<Name>wefwef</Name>
<Qlid>3333</Qlid>
<Manager>1</Manager>
</Person>
<Person>
<Id>4</Id>
<Name>batman</Name>
<Qlid>6723</Qlid>
<Manager>3</Manager>
</Person>
<Person>
<Id>5</Id>
<Name>batman</Name>
<Qlid>6723</Qlid>
<Manager>3</Manager>
</Person>
</Persons>
edit2: ok sorry guys, it was something really stupid . It was a circular loop I thought I had made a shortcut to the xml file on my desktop but instead accidentaly made a copy. person 1 had person 3 as its manager who had person 1 as manager in the file the program was reading while I was editing the copy
[Speculation] You may be crashing due to a stack overflow caused by infinite recursion. Does your contain a member whose manager is the id itself? This would cause your recursion to never end and lead to a stack overflow.
private int getTotalChildren(int id)
{
int total=0;
for (int i = 0; i < persons.Count;i++ )
{
if (persons[i].Manager == id)
{
total += 1;
if(persons[i].Manager != persons[i].Id)
{
total += getTotalChildren(persons[i].Id);
}
}
}
return total;
}
You aren't specifying the child nodes anywhere. You always look at persons, which isn't changing.
Internally, Silverlight has a "recursion limit" designed to help avoid code that freezes the user's browser. If you Google around for "Silverlight recursion" or similar you'll find a few links.
I don't know a ton about it, but my guess is that you'll simply need to do this a different way.
Protip: consider a for/while loop instead of incurring the frame memory overhead associated with recusion for simple scenarios like this.
Remember, everything you can accomplish with recusion can be accomplished without it. A seasoned developer knows when to sacrifice performance for readability.
精彩评论