C# extension method for a method group

送分小仙女□ 提交于 2019-12-01 17:19:29

According to Eric Lippert blog method group is typeless expression. And you can't do anything, just deal with it.

That's exact reason why you can't implicitly cast it to specific delegate and add extension method to it

You are able to write extension methods for delegates. In your example:

Why can't I just use a.Next.AddCaching() ?

In that question, a.Next isn't a type. Extension methods only work for types. Think about it. In your AddCaching extension method, what would you write after this? You need a type. In this case, you used the delegate Func<TKey,TVal>. That means it'll extend that delegate. For you example to compile, you need to write:

((Func<int,int>)a.Next).AddCaching<int,int>()

This will compile properly. Additionally, since you are defining the generic types in the delegate, you can actually call it like this:

((Func<int,int>)a.Next).AddCaching()

It'll know it is using <int,int> from the delegate.

So, you were close, you just needed to cast a.Next to a type, the delegate Func<int,int> for it to compile. It is the same rules that apply to extending any other type in the language.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!