Can Extension Methods Be Called From The Immediate

2020-08-10 09:55发布

问题:

I ask the question because whenever I attempt to call an extension method from the Immediate window in Visual Studio 2010 I get the following error:

System.Collections.Generic.IEnumerable' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)

If the Immediate window doesn't support extension methods, then why is it that when I type my variable (of type IEnumerable<QueryFilter>) followed by a dot, the IntelliSense lists all the extension methods?

There is nothing wrong with what I am typing in the Command window because if I copy and paste it into my code file and run, it works.

With Visual Studio 2012 doing the same thing for the same solution works fine. If I switch back to VS2010 and the problem persists.

回答1:

Extention methods are syntax sugar. Actually they are implemented static with the this keyword. You can call any extention method using the static method that provides the extention method. Then you should pass the object that is being extended as the first parameter.



回答2:

It's because the System.Linq namespace is not imported in the current context you are while debugging.

Add

using System.Linq;

in your code.

Example with Visual Studio 2010:

First times with System.LINQ imported, then without using System.LINQ.

EDIT: If the namespace is imported and IntelliSense is displaying the methods, then it might be a bug of the Immediate window. See this bug entry on connect.



回答3:

Extension methods are just static methods.

You should be able to use e.g. System.Linq.Enumerable.ToList()



回答4:

The extension method translates to "Enumerable.ToList" The compiler would normally convert

myList.Tolist();

To:

Enumerable.ToList(myList);

during compile time. I believe you can use extension methods from the quickwatch window if you so wanted to.



回答5:

This behaviour is caused by Code Contracts, and is not limited to just the Immediate window but also the Conditional Breakpoints window too.

Update March 01, 2016: Found this MSDN Question asking why type resolution is not working in my watch windows. The behaviour described is exactly the same as I experience when using the Immediate Window. The cause is also attributed to CodeContracts and a bug report has been filed on Microsoft Connect. Whether or not the bug is resolve is not indicated.