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

标签 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;
     }
}

这是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;
         }
      }

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

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

最佳答案

由于 ITransaction 继承自 IDisposable,因此实现者可能已将 IDisposable 实现为 explicit interface implementation。 ,在这种情况下,需要强制转换才能访问已实现的成员。

在这种情况下,转换确保调用将调用 IDisposable.Dispose 方法。完成类型转换以涵盖所有基地。

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

关于c# - 在调用 Dispose() 之前转换为 IDisposable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7051864/

相关文章:

c# - 洗牌树(递归)

c# - 使用 System.Windows.Forms.Timer.Start()/Stop() 与 Enabled = true/false

c# - 将OpenCV C++重写为EmguCV C#-如何使用指针?

java - 如何在java中将字符串转换为corelabel?

Swift:使用 as/as 进行转换有什么区别?/as!关键字和 C 风格的转换?

c# - using block 是否保证对象在 block 结束之前不会被释放?

c#-4.0 - 与 IDisposable 混淆

WPF - 是否必须处置 HwndSource?

c# - MVC 3 JsonResult 没有 d 属性

c# - 如何转换 GroupedEnumerable?