Lambda functions in generic C# method -


i'm trying better understand lambda expressions generic methods, have code opening connection , getting information session use.

my goal pass in object of type t can data fixture inside lambda expression.

 protected t getdatafromfixture<t>(int fixture_id, ttfixture fixture, func<t, t> lambda)  {      var fixtures = session.allfixtures;      fixture = fixtures.containskey(fixture_id) ? fixtures[fixture_id] : null;      if (fixture != null)      {           return lambda(t);      }       return default(t);  }  

question is: how pass through lambda function openconnectionwithfixtureobject can access fixture object , return type t

something like..

string total; ttfixture fixture; openconnectionwithfixtureobject<stattotallist>(_fixtureuid, fixture, (stattotalsforoverview) =>  {     total; = fixture.mytotal(); }); 

i don't think logic far off, i'm unfamiliar func<t,tresult> , generics . assistance appreciated!

i don't think there inherently wrong approach, there problems implementation in post - mainly, not well-typed , not compile.

consider updated version notes

protected t openconnectionwithfixtureobject<t>(     int fixture_id, /* #1 */ func<t, t> decorate)      t : class /* #3 */ {      // ..      var fixtures = mymobilesession.current.myclub.mysport.allfixtures;      t fixture = fixtures.containskey(fixture_id)          ? fixtures[fixture_id] t  /* #3 */          : null;      if (fixture != null)      {        /* #2 */        return decorate(fixture);      }      // .. }  openconnectionwithfixtureobject<stattotallist>(_fixtureuid, /* #1 */     /* #4 */     (stattotalsforoverview) => {         stattotalsforoverview.total = fixture.mytotal();         return stattotalsforoverview;     }); 
  1. removed ttfixture fixture parameter/argument, because made no sense id lookup-up , result in error due re-declaration of fixture.

  2. the fixture expression needs typed t can passed func<t,..>. in case as operator can used - if found value not assignable, fixture null. (alternatively, cast-and-guard have been used without adding class restriction on t.)

  3. a func<t,..> accepts argument of type t. however, t generic parameter , not value of type t. such, lambda(t) in original code did not make sense. solution use actual (fixture) object/value.

  4. the function accepts func<t,t> , not action<t>. inclusion of return keyword in lambda syntax makes result in function. however, makes more sense accept action<t> start, unless function can return different object.

also, in c# "lambda [expressions]" refers syntax used created corresponding action-func-expression-etc value - beyond there no "lambda type".


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -