c# - 在 using block 中使用 'as IDisposable'

标签 c# idisposable using

编辑:我的问题不是关于 using block 及其工作原理。我的问题是关于这两种方法的区别,如下所示。

我正在阅读 CQRS Journey Guide,但我不明白这行代码:

using (repo as IDisposable)

这是什么意思?为什么将它用作 IDisposable?在典型的 using block 中,不需要将其用作 IDisposable:

using (var repo = this.respositoryFactory()) { // ... }

知道为什么作者用第一种方式而不是第二种方式写它吗?

这是出现该代码的方法:

private Conference.Web.Public.Models.Conference GetConference(string conferenceCode)
{
    var repo = this.repositoryFactory();
    using (repo as IDisposable)
    {
        var conference = repo.Query<Conference>()
            .First(c => c.Code == conferenceCode);
        var conferenceModel =
        new Conference.Web.Public.Models.Conference
        {
            Code = conference.Code,
            Name = conference.Name,
            Description = conference.Description
        };
        return conferenceModel;
    }
}

最佳答案

Any idea why the authors wrote it the first way instead of the second way?

这通常是由于对语言特性的误解。您编写它的方式是用 C# 编写它的惯用方式:

using (var repo = this.respositoryFactory()) 
{

作者方法的唯一真正优势是如果 repositoryFactory可能会返回一个不实现 IDisposable 的类型.通过 using (repo as IDisposable) 编写代码,相同的代码可以处理非一次性类型。

大多数时候,这不是问题。然而,工厂可以有选择地返回IDisposable。类型。例如,假设此方法是在泛型类中完成的,并且 repositoryFactory返回了 IRepository<T> , type 可能实现也可能不实现 IDiposable 是可能的。 ,在这种情况下,这种方法可以处理这两种情况,而无需强加 IDisposable。对泛型类型的约束。

关于c# - 在 using block 中使用 'as IDisposable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20011148/

相关文章:

c# - 使用 Linq to Entities 进行分组和多重排序

c# - WPF-使按钮的凹陷效果变慢

c# - 传递给 IDisposable 对象的引用的类是否也应该是 IDisposable 并在处置时将它们设置为 null?

java - 我必须使用方法的返回值吗?

c++ - 在 C++ 模板中使用 'using' 的正确做法

c# - 我可以通过堆栈跟踪检索实际的代码行吗?

c# - 如何根据角色加载不同的 _layout.cshtml?

.net - WPF 窗口类的 IDisposable 成员

c# - 如何处理我们没有引用的一次性元素?

php - 我想在mysql中使用php实现行级锁定