Why can't these type arguments be deduced?

Possible duplicate:
The general conclusion of type C # 3.0 is the transfer of a delegate as a function parameter

Why can't arguments like the following code sample be called in the Main call?

 using System; class Program { static void Main(string[] args) { Method(Action); } static void Action(int arg) { // ... } static void Method<T>(Action<T> action) { // ... } } 

The following error message will appear:

error CS0411: type arguments for the Program.Method<T>(System.Action<T>) method Program.Method<T>(System.Action<T>) cannot be taken out of use. Try explicitly specifying type arguments.

+6
source share
3 answers

The problem is that Action (other than an existing type, rename it) is actually a group of methods that converts to the delegate type Action<int> . The I / O mechanism cannot infer a type because the expressions of the method group are irrelevant. If you actually passed a group of methods to Action<int> , then the type-output is successful:

 Method((Action<int>)Action); // Legal 
+2
source

Just put this compiler, I understand what you mean.

I think because Action used as a group of methods, but it is not an Action<int> .

If you apply it to this type, it will work:

 Method((Action<int>)Action); 
0
source

It works:

  static void Main(string[] args) { Method<int>(Action); } static void Action(int arg) { // ... } static void Method<T>(Action<T> action) { // ... } 
0
source

Source: https://habr.com/ru/post/896911/


All Articles