你如何处理IDisposableobject的创建一个LINQ EX pression里面? [英] How do you dispose of IDisposableobject create inside of a Linq expression?

查看:153
本文介绍了你如何处理IDisposableobject的创建一个LINQ EX pression里面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的LINQ允许你创建新的对象的查询EX pression内。当你有一个封装列表生成类中这是非常有用的。我想知道你是如何处理那些需要它创建的对象呢?

Linq allows you to create new object inside of a query expression. This is useful when you have classes that encapsulate generation of a list. I’m wondering how you dispose of objects that are created that need it?

例如:

class Generator
{
    public IEnumerable<int> Gen(int size)
    {
        return Enumerable.Range(0, size);
    }
}

class bar
{
    public void doit()
    {
        var foo =
            from r in Enumerable.Range(1, 3)
            from g in new Generator().Gen(r)
            select g;
    }
}

这将创建3个发电机对象将被垃圾在某些时候收集。如果发电机是IDisposable的我怎么会得到的Dispose()调用?

This will create 3 Generator objects that will be garbage collected at some point. If Generator was IDisposable how would I get the Dispose() call?

推荐答案

确定;我希望这是巧合,而是:的SelectMany;结合了IDisposable和LINQ ,这(与自定义的SelectMany 实施)将允许:

OK; I'm hoping this is coincidence, but: SelectMany; combining IDisposable and LINQ, which (with the custom SelectMany implementation) would allow:

    var foo =
        from r in Enumerable.Range(1, 3)
        from gen in new Generator()
        from g in gen.Gen(r)
        select g;

(注意,我的假设的存在是一个明智的理由,每做研究

(note that I'm assuming there is a sensible reason to do this per r)

的SelectMany

或与使用()扩展方法(而不是的SelectMany ):

or with the Using() extension method (instead of SelectMany):

    var foo =
        from r in Enumerable.Range(1, 3)
        from gen in new Generator().Using()
        from g in gen.Gen(r)
        select g;

使用

这篇关于你如何处理IDisposableobject的创建一个LINQ EX pression里面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆