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; });
removed
ttfixture fixture
parameter/argument, because made no sense id lookup-up , result in error due re-declaration offixture
.the
fixture
expression needs typedt
can passedfunc<t,..>
. in caseas
operator can used - if found value not assignable,fixture
null. (alternatively, cast-and-guard have been used without adding class restriction ont
.)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.the function accepts
func<t,t>
, notaction<t>
. inclusion ofreturn
keyword in lambda syntax makes result in function. however, makes more sense acceptaction<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
Post a Comment