开发者

Why does a delegate with no parameters compile?

开发者 https://www.devze.com 2022-12-27 09:08 出处:网络
I\'m confused why this compiles: private delegate int MyDelegate(int p1, int p2); private void testDelegate()

I'm confused why this compiles:

    private delegate int MyDelegate(int p1, int p2);

    private void testDelegate()
    {
        MyDelegate imp = delegate 
        {
            return 1;
        };
    }

MyDelegate should be a pointer to a method that takes two int parameter开发者_运维知识库s and returns another int, right? Why am I allowed to assign a method that takes no parameters?

Interestingly, these doesn't compile (it complains about the signature mismatches, as I'd expect)

    private void testDelegate()
    {
        // Missing param
        MyDelegate imp = delegate(int p1)
        {
            return 1;
        };

        // Wrong return type
        MyDelegate imp2 = delegate(int p1, int p2)
        {
            return "String";
        };
    }

Thanks for any help!

Ryan


Your first example is short-hand syntax if the delegate doesn't need the parameters. If you need even one of them, you need to provide them all, which is why the first part of the second example won't compile.


Well, in the first sample the compiler can easily see that no parameters are used, and substitute a few dummies.

This looks like a design decision, somewhere on the road from specify-everything in .NET 1, through anonymous methods in .NET 2 to lambdas in .Net 3

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号