内置延迟执行的 .Net IEnumerable 类?
我正要构建自己的 IEnumerable 类,该类在第一次迭代它时对所有项目执行一些操作,然后我开始想知道,框架是否已经有我可以使用的东西?
这是我正在构建的内容,以便您了解我在寻找什么:
public class DelayedExecutionIEnumerable<T> : IEnumerable<T>
{
IEnumerable<T> Items;
Action<T> Action;
bool ActionPerformed;
public DelayedExecutionIEnumerable(IEnumerable<T> items, Action<T> action)
{
this.Items = items;
this.Action = action;
}
void DoAction()
{
if (!ActionPerformed)
{
foreach (var i in Items)
{
Action(i);
}
ActionPerformed = true;
}
}
#region IEnumerable<IEntity> Members
public IEnumerator<T> GetEnumerator()
{
DoAction();
return Items.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
DoAction();
return Items.GetEnumerator();
}
#endregion
}
I was about to build my own IEnumerable class that performs some action on all items the first time something iterates over it then I started wondering, does the framework already have something that I could use?
Here's what I was building so you have an idea what I'm looking for:
public class DelayedExecutionIEnumerable<T> : IEnumerable<T>
{
IEnumerable<T> Items;
Action<T> Action;
bool ActionPerformed;
public DelayedExecutionIEnumerable(IEnumerable<T> items, Action<T> action)
{
this.Items = items;
this.Action = action;
}
void DoAction()
{
if (!ActionPerformed)
{
foreach (var i in Items)
{
Action(i);
}
ActionPerformed = true;
}
}
#region IEnumerable<IEntity> Members
public IEnumerator<T> GetEnumerator()
{
DoAction();
return Items.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
DoAction();
return Items.GetEnumerator();
}
#endregion
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
迭代器 和 yield 允许您轻松创建自己的惰性枚举器序列。
同样在您的情况下,您可以轻松滥用 LINQ 的 Select 方法。
或许可以把它包起来?
(手写未测试代码,谨慎使用)
Iterators and yield allows you to easily create your own lazy enumerator sequence.
Also in your case, you could easily abuse Select method of LINQ.
Maybe wrapping it up?
(hand-written not tested code, use with caution)
我不确定是否有东西完全符合您想要做的事情,但我建议您使用 Lazy为此,它将处理线程安全问题(对于每个单独的项目):
I'm not sure there is something that does exactly what you are trying to do, but I would recommend you to use Lazy<T> for this, it will take care of Thread safety issues (for each individual item):