Optional parameters on delegates doesn't work properly [duplicate]

青春壹個敷衍的年華 提交于 2019-11-29 15:03:35

Optional parameters are for use on the calling side - not on what is effectively like a single-method-interface implementation. So for example, this should compile:

delegate void SimpleDelegate(bool x = true);

static void Main()
{
    SimpleDelegate x = Foo;
    x(); // Will print "True"
}

static void Foo(bool y)
{
    Console.WriteLine(y);
}

What will happen test(false)? It will corrupt the stack, because signatures must match.

Try this way:

static int f(bool a)
{
  return 4;
}

Because optional parameters do not change the underlying signature of the method, which is important to delegates.

What your code is expecting is the optional parameter to not be in the method signature if you don't use it - this is incorrect.

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