简体   繁体   中英

why are lambdas & anonymous methods not allowed on the left side of the is or as operator?

Lambdas are not allowed on the left side of the is or as operator. MSDN

A clear explanation with an real example would be appreciated?

Lambda没有类型,因此,使用检查没有type的值的类型的运算符是没有意义的。

I suspect that it's not related to the following case:

Func<string> x = () => "";  
bool result = x is Func<string>;

But to this case:

// This won't compile
if((() => "") is Func<string>)
{
}

...or:

// This won't compile too
Func<string> func = (() => "") as Func<string>;

Lambda expressions and anonymous methods have no type per se, but they're useful when using delegate type auto-inference:

// C# compiler understands that the right part should be Func<string>
// because the expression signature and return value matches Func<string>
Func<string> func = () => "hello world";

MSDN states that is and as can't be used with anonymous methods and lambda expressions because they've no type until they're infered to some actual delegate type or expression tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM