C#代码简化查询:顺序Foreach循环
发布时间:2020-12-15 07:43:36 所属栏目:百科 来源:网络整理
导读:假设我有一些看起来像这样的代码: 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) } 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: a First: b First: c Second: a Second: b Second: c (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Bindable Flex中Bindable的原理
- 运维危矣?Oracle 发布「自动驾驶」的数据库 18c
- cocos2d-js 3.0 RC0 手动绑定 C++调用js,js调用C++ jsb
- xml.etree.ElementTree — The ElementTree XML API(1)
- XML和HTML对比
- oracle 常用函数
- sysbench对postgresql数据库进行oltp测试
- ruby-on-rails – Rails:以ZIP格式输出的即时流式传输?
- oracle11g – Oracle Warehouse Builder中记录链接的匹配合
- 结构 – 无法在Swift中的“Y”中分配给“X”