在using块中使用"as IDisposable" [英] Using 'as IDisposable' in a using block

查看:78
本文介绍了在using块中使用"as IDisposable"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题不是关于using块及其工作方式.我的问题是两种方法的区别,如下所示.

My question isn't about a using block and how it works. My question is about the difference in the two ways to do it, shown below.

我正在阅读《 CQRS旅程指南》,但我不理解以下代码行:

I'm reading the CQRS Journey Guide, and I don't understand this line of code:

using (repo as IDisposable)

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

What does that mean? Why use it as IDisposable? In a typical using block, one doesn't need to use it as IDisposable:

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

您知道为什么作者以第一方式而不是第二方式来编写它吗?

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

此代码显示的方法:

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#编写的惯用方式:

This is often due to a misunderstanding of the language feature. The way you wrote it is the idomatic way to write it in C#:

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

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

The only real advantage to the author's approach would be if repositoryFactory could, potentially, return a type which doesn't implement IDisposable. By writing the code via using (repo as IDisposable), the same code could handle non-disposable types.

大多数时候,这不是问题.但是,工厂可能会可选地返回IDisposable类型.例如,假设此方法是在通用类中完成的,并且repositoryFactory返回了IRepository<T>,则该类型可能实现也可能未实现IDiposable,在这种情况下,该方法将处理两种情况而不会强加通用类型的IDisposable约束.

Most of the time, this isn't an issue. However, it would be possible that the factory could optionally return an IDisposable type. As an example, suppose this method was done within a generic class, and repositoryFactory returned an IRepository<T>, it would be possible that type may or may not implement IDiposable, in which case this approach would handle both cases without imposing an IDisposable constraint on the generic type.

这篇关于在using块中使用"as IDisposable"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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