c# - 有没有办法让 using 语句带有动态创建的目标?

标签 c# .net idisposable using-statement

假设我定义了一个类 MyDisposable : IDisposable。我知道我可以提供 IDisposable 的硬编码列表反对 using声明:

using (MyDisposable firstDisposable = new MyDisposable(),
    secondDisposable = new MyDisposable())
{
    // do something
}

现在假设我有几个方法可以对我的一次性对象集合执行操作,我想在 using 语句中执行此操作。它可能看起来像这样(但这当然不起作用,因为 using block 需要一个或多个 IDisposable 对象,而我传递的是单个集合对象):

using (var myDisposables = GetMyDisposables())
{
    foreach (var myDisposable in myDisposables)
    {
        DoSomething(myDisposable);
        DoSomethingElse(myDisposable);
    }
}

为了清楚起见,以下是其他方法:

static List<MyDisposable> GetMyDisposables()
{
    throw new NotImplementedException(); // return a list of MyDisposable objects
}

static void DoSomething(MyDisposable withMyDisposable)
{
    // something
}

static void DoSomethingElse(MyDisposable withMyDisposable)
{
    // something else
}

有什么方法可以使用 using 语句来实现吗?还是我只需要扔掉声明并手动处理?

最佳答案

您可以采取的一种方法是创建一个 IDisposable 对象的集合,它也是 IDisposable:

class CollectionOfDisposable<T> : IDisposable where T : IDisposable  {
    public IList<T> Members {get; private set;}
    public CollectionOfDisposable(IEnumerable<T> members) {
        Members = members.ToList();
    }
    public void Dispose() {
        var exceptions = new List<Exception>();
        foreach (var item in Members) {
            try {
                item.Dispose();
            } catch (Exception e) {
                exceptions.Add(e);
            }
        }
        if (exceptions.Count != 0) {
            throw new AggregateException(exceptions);
        }
    }
}

现在你可以这样写了:

using (var myDisposables = GetMyDisposables()) {
    foreach (var myDisposable in myDisposables.Members) {
        DoSomething(myDisposable);
        DoSomethingElse(myDisposable);
    }
}

static CollectionOfDisposable<MyDisposable> GetMyDisposables() {
    throw new NotImplementedException(); // return a list of MyDisposable objects
}

关于c# - 有没有办法让 using 语句带有动态创建的目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38101734/

相关文章:

c# - 如果 using block 返回,是否会释放 IDisposable?

c# - 如何将控件绑定(bind)到 DataGridView

c# - WCF maxBytesPerRead 限制为 4096

c# - 使用wpf绘制六棱柱

.net - 如何在 .NET 中比较两个盒装数字是否相等?

c# - 我是否应该在共享进程生命周期的对象上调用 dispose?

c# - 一次性对象克隆会导致 C# 中的内存泄漏吗?

c# - IE 9 中的 JavaScript 问题

c# - 无法安装 .NET 框架,因为 Windows 认为安装了更新版本

c# - 如何在不将页面加载到浏览器的情况下刷新页面?