C#到VB .NET收益回报转换收益、VB、NET

由网友(爱她毁我i)分享简介:这是什么片段在VB .NET的翻译?公共静态的IEnumerable< TSource>其中,< TSource>(这IEnumerable的< TSource>资源,FUNC< TSource,布尔> predicate){的foreach(源TSource元){...

这是什么片段在VB .NET的翻译?

 公共静态的IEnumerable< TSource>其中,< TSource>(
这IEnumerable的< TSource>资源,
FUNC< TSource,布尔> predicate)
{
  的foreach(源TSource元)
  {
    如果(predicate(元))
    得到的回报元素;
  }
}
 

解决方案

这里的问题未进行转换的扩展方法 - 这是转换迭代器块(该方法使用收益率回报 VB没有任何相当于语言结构 - 你必须创建自己的实施的IEnumerable< T> 它做了筛选,然后返回一个实例该类从扩展方法。

这正是C#编译器做的,但它隐藏在幕后。

要注意的一点,这可能不是很明显,否则:的IEnumerator< T> 工具的IDisposable ,和的foreach 循环部署的迭代器结束。这是非常重要的 - 所以,如果你的不的创建自己执行这一(和我建议你不这样做,坦率地说),你需要调用处置从迭代器返回 source.GetEnumerator()在自己的处置方法。

What's the translation of this snippet in VB .NET?

public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, Boolean> predicate)
{
  foreach (TSource element in source)
  {
    if (predicate(element))
    yield return element;
  }
}
VB NET

解决方案

The problem here isn't converting an extension method - it's converting an iterator block (the method uses yield return. VB doesn't have any equivalent language construct - you'd have to create your own implementation of IEnumerable<T> which did the filtering, then return an instance of the class from the extension method.

That's exactly what the C# compiler does, but it's hidden behind the scenes.

One point to note, which might not be obvious otherwise: IEnumerator<T> implements IDisposable, and a foreach loop disposes of the iterator at the end. This can be very important - so if you do create your own implementation of this (and I'd recommend that you don't, frankly) you'll need to call Dispose on the iterator returned from source.GetEnumerator() in your own Dispose method.