Optional parameters on delegates doesn't work

2019-01-28 04:19发布

This question already has an answer here:

Why this piece of code does not compile?

delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}

4条回答
何必那么认真
2楼-- · 2019-01-28 04:39

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

查看更多
在下西门庆
3楼-- · 2019-01-28 04:44

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);
}
查看更多
Lonely孤独者°
4楼-- · 2019-01-28 04:45

Try this way:

static int f(bool a)
{
  return 4;
}
查看更多
ら.Afraid
5楼-- · 2019-01-28 04:50

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.

查看更多
登录 后发表回答