开发者

Weird extension method issue with inheritance

开发者 https://www.devze.com 2023-03-23 21:50 出处:网络
I\'m trying to extend Page class to add some new functionality (ease of use for some methods as they will be called directly within the code of that page) in ASP.NET, and I\'m getting a weird error:

I'm trying to extend Page class to add some new functionality (ease of use for some methods as they will be called directly within the code of that page) in ASP.NET, and I'm getting a weird error:

My method is called SetQuery,

if I type SetQuery in a Page class, it is not recognized (yes, I've added using [Namespace];),

if I type base.SetQuery it is seen in IntelliSense, but doesn't compile saying no method or extension method is actually found in Page,

if I type (this as Page).SetQuery it is recognized and works.

Especially the second case seems to be a bug to me, as IntelliSense recognizes it as an extension method, but no compilation.

Is there any 'more natur开发者_开发知识库al' way to type SetQuery as I go, without casts etc.?


Extension methods always require an (explicit) target object, so it is impossible to call an extension method via just TheMethodName(). I suspect that if you type:

this.SetQuery();

it will work. There is never an implicit this. with extension methods. Odd but true.

The above explains why SetQuery() doesn't work; base.SetQuery() won't work, since the extension method is defined for Page, not for the base-class. (this as Page).SetQuery() will work for the same reasons as this.SetQuery(), and actually since this as Page is obviously true, the compiler will treat that as a no-op - i.e. this.SetQuery() and (this as Page).SetQuery() should generate the same IL (as long as the actual page doesn't have a more specific SetQuery() method, obviously).

0

精彩评论

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

关注公众号