在调用 Dispose() 之前转换为 IDisposable

yan*_*hon 5 c# casting idisposable

在调用Dispose()之前转换为IDisposable的原因是什么?

public interface ITransaction : IDisposable
{}
.
.
.

//in some other class:
public void EndTransaction(ITransaction transaction)
{
     if (transaction != null)
     {
          (transaction as IDisposable).Dispose(); 
          // is the following code wrong? transaction.Dispose()

          transaction = null;
     }
}
Run Code Online (Sandbox Code Playgroud)

这是 ITransaction 的具体实现之一:

public class NHibernateTransaction : ITransaction
{

     public NHibernateTransaction(NHibernate.ITransaction transaction)
     {
          this.Transaction = transaction;
     }

     protected NHibernate.ITransaction Transaction { get; private set; }

     public void Dispose()
     {
         if ( this.Transaction != null )
         {
             (this.Transaction as IDisposable).Dispose(); // this is NHibernate  ITransaction object
              this.Transaction = null;
         }
      }
Run Code Online (Sandbox Code Playgroud)

}

我在存储库模式的开源实现中多次看到该代码片段,但我似乎无法理解转换背后的原因。在if 子句中直接调用transaction.Dispose()应该可以正常工作。我错过了什么?

原始代码可以在这里找到: NHibernateTransaction.cs

Ode*_*ded 3

由于ITransaction继承自IDisposable,实现者可能已实现IDisposable显式接口实现,在这种情况下,需要进行强制转换才能访问实现的成员。

在这种情况下,转换可确保调用将调用该IDisposable.Dispose方法。演员阵容已覆盖所有基地。

如果ITransaction不继承自IDisposable,但实现者继承了,则需要进行强制转换才能Dispose调用。如果实现者没有实现,这种情况可能会失败(抛出异常)IDisposable