Overloading in local methods and lambda

徘徊边缘 提交于 2019-12-19 17:04:55

问题


static void Main() {
  void TestLocal() => TestLocal("arg");
  TestLocal("arg");
}
static void TestLocal(string argument) {
}

In this example, local function has the same name as another method, which I want to overload. But this method is invisible from inside of this function, and even from inside of Main(). The same is for lambdas:

static void Main() {
  Action TestLambda = () => TestLambda("arg");
}
static void TestLambda(string argument) {
}

I understand, why lambda hides outer method - because it is a local variable, and local variables always work this way. But I don't see any reason for local functions hide and not overload outer methods - it could be very useful for reducing amout of arguments in local scope, doing some kind of carrying.

Why local functions hide methods?

EDIT:

I can imagine an example where it gets complicated

void Bar(short arg) {
  Console.WriteLine("short");
}
void Bar(byte arg) {
  Console.WriteLine("byte");
}
void Test() {
  void Bar(int arg) {
    Console.WriteLine("int");
  }
  Bar(0);
}

It was already complicated enough with argument type resolution. If they added overloading to local methods, it would be one more stupid task for job interviews and one more huge task for compiler makers. And there are also virtual and new methods...


回答1:


Why local functions hide methods?

Basically it's introducing the method name into the declaration space inside the method. Within that declaration space, the name only refers to the local method... just as it does for a local variable. I think that's reasonably consistent with the way that names introduced into methods have always worked.

I'd personally advise against trying to do this anyway, as it'll cause confusion, but if you really need to refer to the class method, just make it explicit:

ClassName.TestLocal("arg");

What I do think could be fixed is that local methods can't be overloaded between themselves. You can't write:

void Foo()
{
    void Method(int x) {}
    void Method(string y) {}
}

This is for a related reason - a method's declaration space can't include the same name twice, whereas a class's declaration space can do so, in terms of method overloading. Maybe the rules will be loosened around this...



来源:https://stackoverflow.com/questions/48579516/overloading-in-local-methods-and-lambda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!