问题
Imagine I have this code:
public void Foo()
{
// Do bar work
// Do baz work
// Do foobar work
}
And I realize I can (and should because it was doing more than one thing) refactor it into:
public void Foo()
{
bar();
baz();
foobar();
}
private void bar() { /* do bar work */ }
private void baz() { /* do baz work */ }
private void foobar() { /* do foobar work */ }
But then I realize I will never use these functions outside of Foo()
, so those functions are just cluttering the main page and the auto-complete. I could get away with this:
public void Foo()
{
bar();
baz();
foobar();
void bar() { /* do bar work */ }
void baz() { /* do baz work */ }
void foobar() { /* do foobar work */ }
}
Which would make things neater and less clutter, but all I've really done now is made the method even longer instead of shorter.
回答1:
Which would make things neater and less clutter, but all I've really done now is made the method even longer instead of shorter.
No, you haven’t. You are basically saying something similar to not being any difference between a class with one method that does a whole lot of stuff and a class that does the same job but with multiple shorter and easier to mantain methods.
Your local functions are just like methods, the fact that they are contained within another method doesn’t preclude that the whole is much easier to maintain; functionality is encapsulated in clearly defined scopes.
回答2:
I do love the idea of @Mark Benningfield of using partial files (it is what I do when my classes are too much big and there are one or two uber-methods)
My only problem with local functions is that they could capture variables, and it isn't always clear if the are doing it or not. So by "promoting" a "real" method to "local" you are enlarging the visibility it has.
回答3:
Local functions provide advantages over anonymous functions because anonymous functions can only be invoke via delegates which, besides the memory allocation for the delegate, is a costlier invocation.
Local functions can be recursive without the trickery needed by delegates:
int f(int i) => i >= 1 ? i * f(i - 1) : 1;
Func<int,int> d = null;
d = (int i) => i >= 1 ? i * d(i - 1) : 1;
Like anonymous delegates, local functions, unlike top level methods, can capture local variables. And because thy are local, they can't be invoked by other functions.
回答4:
Use anonymous functions:
public void Foo()
{
Action bar = delegate () { /* do bar work */ };
Action baz = delegate () { /* do baz work */ };
Action foobar = delegate () { /* do foobar work */ };
bar();
baz();
foobar();
}
or lambda expression syntax:
public void Foo()
{
Action bar = () => { /* do bar work */ };
Action baz = () => { /* do baz work */ };
Action foobar = () => { /* do foobar work */ };
bar();
baz();
foobar();
}
来源:https://stackoverflow.com/questions/50438563/is-there-any-point-in-using-local-functions-if-to-only-use-them-once