Why can't these type types be inferred?

I have the following code:

public static class CardView {
    public static object Column<TModel, TResult>(Func<TModel, TResult> field) {
        return null;
    }
}

public class Person 
{
    public string Name { get; set; }
    public bool Gender { get; set; }
}

void Main()
{
    var model = new Person() { Name = "Andre", Gender = true };

    var b = CardView.Column(model => model.Name); // ERROR
    // The type arguments for method 'UserQuery.CardView.Column<TModel,TResult>(System.Func<TModel,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
}

For some reason, it cannot deduce common types for a method Column. I need to know why. I cannot refuse type inference and specify types myself, because this is just an example for a big problem, where it will be needed.

EDIT

I made a mistake with the code = / just fixed it

+5
source share
4 answers

In order for the compiler to perform type inference, some type information must be provided to it. In this case, the only information he provided is an untyped lambda expression. The compiler really has nothing to do here.

. - lambda paramater

var b = CardView.Column((Person m) => m.Name);
+7

" , ". , 7.5.2 ( ):

7.5.2.1

Ei:

  • Ei - , (§7.5.2.7) Ei Ti
  • , Ei U xi , U Ti.
  • , Ei U, xi - ref out U Ti.
  • .

7.5.2.7

E T :

  • E - U1... Uk T - V1... Vk, Ui (. 7.5.2.8) Ui Vi.

, . , , , , :

var b = CardView.Column((Person m) => m.Name); 

Func<Person, string>, .

+2

TModel ( , TModel), m.

+1

Your edited code will not compile. You cannot use modellambda as a parameter because you have already declared it a local variable. It looks like you want to tell the compiler what the lambda parameter is Person, using the already declared local type of this type. But that will not work.

The proper way to inform a type compiler is to either declare it explicitly in lambda, as others said:

var b = CardView.Column((Person m) => m.Name); 

or specify type arguments for the general method:

var b = CardView.Column<Person, string>(m => m.Name); 
0
source

All Articles