c# - The type arguments for method cannot be inferred from the usage TModel, TProperty -


public class test { public int id { get; set; } } class program {     static void main(string[] args)     {         var model = new test { id = 222 };         helpers.testmethod(m => model.id); // doesn't work         helpers.testmethod<test, int>(m => model.id); // works         console.readkey();     } }  public class helpers {     public static string testmethod<tmodel, tproperty>(expression<func<tmodel, tproperty>> expression)     {         // work on expression         return string.empty;     } } 

if using @html.textboxfor extension method. don't have specify types this: @html.textboxfor, why this? why have explicitly specify types?

how possible infer model html.textboxfor?? when never specified html.textboxfor<test, int>.

if @ how textboxfor implemented, you'll see it's extension method:

public static mvchtmlstring textboxfor<tmodel, tproperty>(     htmlhelper<tmodel> htmlhelper,     expression<func<tmodel, tproperty>> expression ) 

htmlhelper used infer tmodel, , that's method missing.

public static string testmethod<tmodel, tproperty>(tmodel model, expression<func<tmodel, tproperty>> expression) 

now can call without specifying generic types:

var model = new test { id = 222 }; testmethod(model, m => m.id); // works fine 

you can make extension method, adding this modifier

public static string testmethod<tmodel, tproperty>(this tmodel model, expression<func<tmodel, tproperty>> expression) 

which allow call it

var model = new test { id = 222 }; model.testmethod(m => m.id); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -