C#到VB .NET产生返回转换

Raú*_*Roa 3 .net c# vb.net

这个片段在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;
  }
} 
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

这里的问题不是转换扩展方法 - 它正在转换迭代器块(该方法使用yield return.VB没有任何等效的语言构造 - 你必须创建自己的实现,IEnumerable<T>其中进行了过滤,然后返回一个实例扩展方法中的类.

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

需要注意的一点是,否则可能并不明显:IEnumerator<T>实现IDisposable,并且foreach循环在最后处理迭代器.这可能非常重要 - 所以如果您确实创建了自己的实现(并且我建议您不要,坦率地说),您需要调用Disposesource.GetEnumerator()您自己的Dispose方法返回的迭代器.


bbq*_*bot 5

这个问题已经过时了,但对于来自谷歌的人来说,有一个好消息 - 新版本的VB.NET支持c#yield return运算符(我相信这不是VS.NET 2010/2012 w/.net 4.0).这是转换后的样本:

<System.Runtime.CompilerServices.Extension> _
Public Iterator Function Where(Of TSource)(source As IEnumerable(Of TSource), predicate As Func(Of TSource, [Boolean])) As IEnumerable(Of TSource)
    '' non-lambda version of the method body
    'For Each element As TSource In source
    '    If predicate(element) Then
    '        Yield element
    '    End If 
    'Next
    For Each element As TSource In From item In source Where predicate(item)
        Yield element
    Next
End Function
Run Code Online (Sandbox Code Playgroud)

无需将静态更改为共享,因为必须在自动"共享"或静态的模块中定义VB.NET扩展方法.