请参阅以下代码:
Private Iterator Function QueryCore(ByVal sql As String, Optional ByVal parms() As Object = Nothing) As IEnumerable(Of Object)
Using connection = CreateConnection()
Using command = CreateCommand(sql, connection, parms)
Using reader = command.ExecuteReader()
Do While reader.Read()
Yield reader.ToExpando()
Loop
End Using
End Using
End Using
End Function
<System.Runtime.CompilerServices.Extension> _
Public Function ToExpando(ByVal reader As IDataReader) As Object
Dim dictionary = TryCast(New ExpandoObject(), IDictionary(Of String, Object))
For i As Integer = 0 To reader.FieldCount - 1
dictionary.Add(reader.GetName(i), If(reader(i) Is DBNull.Value, Nothing, reader(i)))
Next i
Return TryCast(dictionary, ExpandoObject)
End Function
ExpandoObject
方法返回时ToExpando
存储在哪里?
我理解遵循这种语法的迭代器:
// Implementing the enumerable pattern
public System.Collections.IEnumerable SampleIterator(int start, int end)
{
for (int i = start; i <= end; i++)
{
yield return i;
}
}
ListClass test = new ListClass();
foreach (int n in test.SampleIterator(1, 10))
{
System.Console.Write(n + " ");
}
当Yield
语句在QueryCore
中运行时,控件不会传递回调用者。这让我很困惑。
答案 0 :(得分:0)
ExpandoObject
由new ExpandoObject()
语句中的dim
表达式在堆上创建。然后它由ToExpando
返回,然后由QueryCore
返回,因为Yield
。控制权由Yield
语句传回。