我有一些数据需要传递给递归函数。我想确保它不会在该函数中更改。我怎样才能做到这一点?
考虑:
static List<Person> GetPeopleWithSameNameAncestors(List<Person> people)
{
return people.Where(person => HasAncestorWithName(person.Parents, person.Name)).ToList();
}
//Here, nameToLookFor is always the same for every outside call to this function
static bool HasAncestorWithName(List<Person> lookIn, String nameToLookFor)
{
return lookIn.Any(p => p.Name == nameToLookFor || (p.Parents != null && HasAncestorWithName(p.Parents, nameToLookFor)));
}
实际情况更复杂,这就是为什么确保 nameToLookFor 不被更改很重要,因为有人可以很容易地做到这一点。哦,我不能碰“Person”类。
如果这不能直接实现,有没有人知道可以安全解决这个问题的模式?