开发者

Delegates with explicit "this" pointer?

Is it possible to adapt a method like this function "F"

class C {
    public void F(int i);
}

to a delegate like Action<C,int>?

I have this vague recollection that Microsoft was working on supporting this kind of adaptation. But maybe I misremembered!

Edit: I know that this doesn't compile in VS2008:

class C {
    public void F(int i);
    void G() {
        Action<C, int> test = this.F;
    }
}

I was just wondering if MS provides a way to do this in the BCL, or if t开发者_StackOverflow社区he feature would be added in a future version.


The easiest way is probably to create a lambda which takes a C and an int, and calls F on the C, passing the int:

Action<C, int> test = (c, v) => c.F(v);

You can also create what's called an open delegate to the instance method C.F, as opposed to the usual type of delegate which is "closed over it's instance parameter". This would be done using reflection and the Delegate.CreateDelegate method. While that would result in a more 'direct' delegate, it is in all likelihood more complex than you require.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜