开发者

Passing Delegate object to method with Func<> parameter

I have a method Foo4 that accepts a parameter of the type Func<>. If I pass a parameter of anonymous type , I get no error. But if I create and pass an object of the type 'delegate' that references to a Method with correct signature, I get compiler error. I am not able to understand why I am getting error in this case.

class Learn6
    {
        delegate string Mydelegate(int a);
        public void Start()
        {
            Mydelegate objMydelegate = new Mydelegate(Foo1);

            //No Error
            Foo4(delegate(int s) { return s.ToString(); });

            //This line gives compiler error.
            Foo4(objMydelegate);

        }

        public string Foo1(int a) { return a.ToString();}



  开发者_Python百科      public void Foo4(Func<int, string> F) { Console.WriteLine(F(42)); }
    }


It works if you pass a reference to the method directly:

Foo4(Foo1);

This is because actual delegates with the same shape are not inherently considered compatible. If the contracts are implicit, the compiler infers the contract and matches them up. If they are explicit (e.g. declared types) no inference is performed - they are simply different types.

It is similar to:

public class Foo
{
    public string Property {get;set;}
}

public class Bar
{
    public string Property {get;set;}
}

We can see the two classes have the same signature and are "compatible", but the compiler sees them as two different types, and nothing more.


Because Func<int, string> and MyDelegate are different declared types. They happen to be compatible with the same set of methods; but there is no implicit conversion between them.


        //This line gives compiler error.
        Foo4(objMydelegate);

        //This works ok.
        Foo4(objMydelegate.Invoke);


depends on the scenario, but in the general case there's no reason to keep around the Mydelegate type, just use Func<int, string> everywhere :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜