我需要知道如何将以下内容转换为VB.net以进行Async / Await项目:
public static class Extensions {
public static IEnumerable<T> Select<T>(
this SqlDataReader reader, Func<SqlDataReader, T> projection) {
while (reader.Read()) {
yield return projection(reader);
}
}
}
用法:
'call the database asynchronously... and 'await' the results
Using reader = Await Db.GetReaderAsync("spGetDashboard", ParamList)
Return reader.Select(Function(r)
Return New DashboardInfo With {.RowNum = CType(r.Item("RowNum"), Long?)}
End Function)
这是我到目前为止所做的:
<Extension()>
Public Function [Select](Of T)(reader As SqlDataReader, projection As Func(Of SqlDataReader, T)) As IEnumerable(Of T)
While reader.Read()
Return CType(projection(reader), IEnumerable(Of T))
End While
End Function
以下是例外:
System.InvalidCastException:无法转换类型的对象 键入'WindowsApplication1.DashboardInfo' 'System.Collections.Generic.IEnumerable`1 [WindowsApplication1.DashboardInfo]'。 在WindowsApplication1.Extensions.Select [T](SqlDataReader阅读器, Func`2投影)in C:\ Dev \ AsyncDbTesting \ AsyncDbTesting \ Library \ Extensions.vb:第523行 在 WindowsApplication1.Process.VB $ StateMachine_1_GetDashboardAsync.MoveNext() 在C:\ Dev \ AsyncDbTesting \ AsyncDbTesting \ Process.vb:第30行 ---从抛出异常的先前位置开始的堆栈跟踪结束--- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务)在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() 在 WindowsApplication1.Form1.VB $ StateMachine_0_Button1_Click.MoveNext() 在C:\ Dev \ AsyncDbTesting \ AsyncDbTesting \ Form1.vb:第17行
答案 0 :(得分:0)
因为您尝试将类型为T
的项目转换为IEnumerable(Of T)
类型而引发异常。
假设您正在使用.Net framework 4.5,您想要的代码是
<Extension()>
Public Iterator Function [Select](Of T)(reader As SqlDataReader, projection As Func(Of SqlDataReader, T)) As IEnumerable(Of T)
While reader.Read()
Yield projection(reader)
End While
End Function
请注意,.Net framework 4.5之前的VB.NET中不存在Yield
和迭代器的概念。