与动态对象一起使用的收益

时间:2017-05-15 22:41:45

标签: c#

请参阅以下代码:

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中运行时,控件不会传递回调用者。这让我很困惑。

1 个答案:

答案 0 :(得分:0)

ExpandoObjectnew ExpandoObject()语句中的dim表达式在堆上创建。然后它由ToExpando返回,然后由QueryCore返回,因为Yield。控制权由Yield语句传回。