vendredi 8 avril 2016

"Object does not match target type" on basic Delegate example

I'm playing around with Delegates, but I'm clearly not grasping something basic.

I've got the following:

class Test
{
    delegate bool Foo();

    public void Run()
    {
        Delegate foo = new Foo((delegate () { return true; }));
        bool result = (bool)foo.Method.Invoke(foo, null);
    }
}

Test test = new Test();
test.Run();

In the above example I encounter an exception: "Object does not match target type."

The following works alright, though:

class Test
{
    delegate bool Foo();

    public void Run()
    {
        Foo foo = new Foo((delegate () { return true; }));
        bool result = foo.Invoke();
    }
}

Test test = new Test();
test.Run();

What's incorrect with my first implementation? Shouldn't I be invoking foo's method, as foo, with no parameters? This would seem equivalent to the latter code.





Aucun commentaire:

Enregistrer un commentaire