从try/catch块中产生返回值



正如Eric Lippert在本文中所描述的,try/catch子句中不允许使用yield return

有没有一种很好的方法,我可以得到这样的东西,而不必手工编写我自己的IEnumerator:

public IEnumerable<Data> GetData()
{
    var transaction = Session.BeginTransaction());
    try 
    {
        IQuery q = CreateQuery(session);
        foreach (var result in q.Enumerable())
            yield return ProjectResult(result);  // <-- doesn't work
        session.Commit();
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        throw;
    }
    finally
    {
        transaction.Dispose();
    }
}

我只需像这样更改事务处理逻辑:

public IEnumerable<Data> GetData()
{
    var transaction = Session.BeginTransaction();
    bool rollback = true;
    try 
    {
        IQuery q = CreateQuery(session);
        foreach (var result in q.Enumerable())
        {
            yield return ProjectResult(result);
        }
        rollback = false;
        session.Commit();
    }
    finally
    {
        if (rollback)
        {
            transaction.Rollback();
        }
        transaction.Dispose();
    }
}

或者如果您的事务支持"dispose意味着回滚,除非它已提交"的想法:

public IEnumerable<Data> GetData()
{
    using (var transaction = Session.BeginTransaction();
    {
        IQuery q = CreateQuery(session);
        foreach (var result in q.Enumerable())
        {
            yield return ProjectResult(result);
        }
        // Commits the tnrasaction, so disposing it won't roll it back.
        session.Commit();
    }
}

refactor

foreach (var result in q.Enumerable()) 
  yield return ProjectResult(result);

放到一个单独的方法中,然后返回结果。

相关内容

  • 没有找到相关文章

最新更新