Passing the same value around in a recursive function?
I've got a recursive function with the s开发者_开发知识库ignature
public static string Recurse(string pattern, ObjectDict dict)
The value of dict
never changes. It kind of bothers me that I should have to carry around dozens of references to it, and pass it around each time I call the function again. Is there a way around this?
By "never changes", I mean after the initial call.
references are extremely lightweight, so don't worry about it.
If you really need to avoid it (and, I don't think you do), consider something like this:
class MyClass
{
private ObjectDict m_dict;
public string Recurse(string pattern, ObjectDict dict)
{
m_dict = dict;
return HelperRecurse(pattern);
}
private string HelperRecurse(string pattern)
{
// do some work. (referring to m_dict)
HelperRecurse(pattern); // Go recursive
return "Hello World";
}
}
By doing this, you are no longer passing around references to the same dictionary, just always accessing a member-object. However, you've lost the static
nature of your function now.
One option is to use a lambda expression to hold the actual logic of the Recurse
function. This can then be called recursively and because it's a lambda it will have access to the dict
object without having to pass it around
public static string Recurse(string initialPattern, ObjectDict dict) {
Func<string, string> inner = null;
inner = pattern => {
// Logic which uses calls to inner for recursion. Has access to dict
// because it's a lambda. For example
if (dict.SomeOperation()) {
return inner(someOtherPattern);
}
return aValue;
};
return inner(initialPattern);
}
Well, the obvious alternative is to make Recurse
an instance method on ObjectDict
if you can. Then you can just call Recurse(pattern)
internally.
If that's not possible for any reason, don't sweat it. In fact, the two options are really very similar - for instance methods, there's effectively an invisible "this" parameter which is passed along first, before the rest of the parameters. You just happen to have put yours at the other end :)
精彩评论