c# - How to combine and simplify the following functions? -


i have number of functions have similar implementations:

private async void buttonsetqmbrakedelay_click(object sender, eventargs e) {     var cells = objectlistview.checkedobjects.cast<qmdevice>().tolist();     if (cells == null)         return;      await task.whenall(cells.select(async c =>     {         bool b = await c.setbrakedelay((uint)numericupdownqmbrakedelay.value);         ...     })); }  private async void buttonpsmoveto_click(object sender, eventargs e) {     var cells = objectlistview.checkedobjects.cast<psdevice>().tolist();     if (cells == null)         return;      await task.whenall(cells.select(async c =>     {         bool b = await c.moveto((float)numericupdownpstargetpos.value, (float)numericupdownpsspeedoverride.value);         ...     })); } 

the difference cast type , body of anonymous function. how can create single method, pass type , anonymous function?

i expect this:

private async void buttonpsmoveto_click(object sender, eventargs e) {     await checkandruncommandasync(psdevice, {         bool b = await c.setbrakedelay((uint)numericupdownqmbrakedelay.value);     ...     }); } 

the method you're describing can written this:

private async task castandapplycheckedobjects<t>(func<t, task> command) {     await task.whenall(objectlistview.checkedobjects.cast<t>().select(command)); } 

then can call this:

private async void buttonpsmoveto_click(object sender, eventargs e) {     await castandapplycheckedobjects<psdevice>(async c => {         bool b = await c.setbrakedelay((uint)numericupdownqmbrakedelay.value);     ...     }); } 

as people have mentioned in comments, don't see point in using cast. if have guarantee items type want, why isn't checkedobjects collection of type? if don't have guarantee, should using oftype or otherwise cast throw exception.


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -