C#代码简化查询:顺序Foreach循环

C#代码简化查询:顺序Foreach循环,第1张

概述假设我有一些看起来像这样的代码: foreach(type x in list y){ //dostuff1(x)}foreach(type x in list y){ //dostuff2(x)}foreach(type x in list y){ //dostuff3(x)}foreach(type x in list y){ //dostuf 假设我有一些看起来像这样的代码:
foreach(type x in List y){   //dostuff1(x)}foreach(type x in List y){   //dostuff2(x)}foreach(type x in List y){   //dostuff3(x)}foreach(type x in List y){   //dostuff4(x)}foreach(type x in List y){   //dostuff5(x)}

我无法将事物组合成一个像这样的大循环

foreach (type x in List y){    //dostuff1(x)    //dostuff2(x)    //dostuff3(x)    //dostuff4(x)    //dostuff5(x)}

这样做会改变顺序.有关在C#中使代码更简单的最佳方法的任何评论?

我想我可以通过创建这样的函数来解决这个问题,虽然我宁愿保持它的方式而不是强迫我的代码的未来读者理解产量:

voID func(type x){    dostuff1(x)    yIEld 0;    dostuff2(x)    yIEld 0;    dostuff3(x)    yIEld 0;    dostuff4(x)    yIEld 0;    dostuff5(x)    yIEld break;}for (int i = 0; i<5; ++i){   foreach (type x in List y)   {       //Call func(x) using yIEld semantics,which I'm not going to look up right Now   }}
解决方法 另一种选择:
List<Action<Foo>> actions = new List<Action<Foo>> {     doStuff1,doStuff2,doStuff3,doStuff4,doStuff5};foreach (Action<Foo> action in actions){    foreach (Foo x in List)    {        action(x);    }}

刚检查,这是有效的.例如:

using System;using System.Collections.Generic;public class Test{    static voID Main(string[] args)    {        var actions = new List<Action<string>> {            First,Second        };        foreach (var action in actions)        {            foreach (string arg in args)            {                action(arg);            }        }    }    static voID First(string x)    {        Console.Writeline("First: " + x);    }    static voID Second(string x)    {        Console.Writeline("Second: " + x);    }}

运行Test.exe a b c的结果

First: aFirst: bFirst: cSecond: aSecond: bSecond: c
总结

以上是内存溢出为你收集整理的C#代码简化查询:顺序Foreach循环全部内容,希望文章能够帮你解决C#代码简化查询:顺序Foreach循环所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1243298.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存