分解骨架处理 (C#)
C# 中是否存在允许抽象循环(或其他)“外部”处理的语言结构?
我有一个相当直接的嵌套结构(例如整数列表的列表)和通过每个最低级别的整数“旋转”的代码。代码并不复杂(也不是特别长),但我有多个函数需要独立地与最低级别“交互”,并且只是复制循环骨架来执行此操作。对我来说似乎是一种浪费。
foreach (list in outerlists)
... a few random lines of structure traversing
foreach (int in list)
do something simple to int
这显然是一个按比例缩小的示例,但我的现实世界是相似的 - 我最终重复复制外部处理以更改相对较少的内部工作线。
我的暂定解决方案是创建一个包含循环的“处理”方法,并采用枚举(或其他)参数来告诉它要调用哪个内部函数。然后在“做某事”级别放置一个 switch 语句来调用正确的子函数。
我走在正确的道路上还是有更简单的方法?我可以使用函数指针的概念摆脱 switch 语句(只需将函数指针传递到处理循环并在执行某些操作级别调用它),但不知道这在 C# 中是否可行?
Is there a language construct in C# that allows the abstraction of loop (or other) "outer" processing?
I have a fairly straight forward nested structure (lists of lists of ints say) and the code to "spin" through each of the lowest level ints. The code isn't complicated (nor particularly long) but I have multiple functions thats need to "interact" with the lowest level independently and have been just copying the loop skeleton to do so. Seems like a waste to me.
foreach (list in outerlists)
... a few random lines of structure traversing
foreach (int in list)
do something simple to int
This is obviously a scaled down example but my real world is similar - I end up copying the outer processing repeatedly to change out relatively few inner lines of work.
My tentative solution is to make a "processing" method that contains the loops and takes an enumeration (or something) parameter to tell it which inner function to call. Then put a switch statement at the "do something" level which calls the correct sub function.
Am I on the right track or is there an easier way? I could get rid of the switch statement with a concept of function pointers (just pass a function pointer into the processing loop and call it at the do something level) but don't know if that is possible in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(详细阐述 Oded 的答案)
假设您总是希望以相同的方式进行迭代,并且复制粘贴的 foreach 之间唯一的不同是最里面的嵌套块,那么您可以将所有循环封装到一个方法中:
该操作可以是任何C# 接受的委托(委托是 C# 对 C/C++ 函数指针的回答):
(elaborating a bit on Oded's answer)
Assuming you always want to iterate the same way and that the only thing different between the copy-pasted foreach's is the innermost nested block then you could encapsulate all the looping into a method:
The action can be any of the formats that C# accepts for delegates (a delegate is C#'s answer to C/C++ function pointers):
您可以传入
Action
委托 -这将是在外循环中执行实际操作的函数。You can pass in an
Action
delegate - this will be the function doing the actual operation within the outer loop.