Home > Backend Development > C++ > Why Can't Implicitly Typed Variables ('var') Hold Anonymous Methods Without Explicit Type Declaration?

Why Can't Implicitly Typed Variables ('var') Hold Anonymous Methods Without Explicit Type Declaration?

Mary-Kate Olsen
Release: 2024-12-31 19:25:10
Original
596 people have browsed it

Why Can't Implicitly Typed Variables ('var') Hold Anonymous Methods Without Explicit Type Declaration?

Why Can't Anonymous Methods Be Assigned to Variables Inferred to the Implicit Type 'Var'?

Consider the following code:

Func<string, bool> comparer = delegate(string value) {
    return value != "0";
};
Copy after login

This code compiles successfully because the inferred type of the lambda expression is a Func delegate. However, the following code does not compile:

var comparer = delegate(string value) {
    return value != "0";
};
Copy after login

The compiler cannot infer the delegate type for the lambda expression in this case. This is because there are infinitely many possible delegate types that could be inferred, and the compiler does not have enough context to determine which one is intended.

For example, the lambda expression could be of type Func, Predicate, or Action. Additionally, the lambda expression could be of type Expression>, which represents an expression treeではなく、委任型です。

To resolve this issue, explicitly specify the delegate type for the lambda expression:

var comparer = (Func<string, bool>)delegate(string value) {
    return value != "0";
};
Copy after login

With this change, the code will compile successfully, and the inferred type of the lambda expression will be Func.

The above is the detailed content of Why Can't Implicitly Typed Variables ('var') Hold Anonymous Methods Without Explicit Type Declaration?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template