PostSharp 一次性属性

PostSharp Disposable Attribute

有人用过 PostSharp Disposable 属性吗?

文档中有一个示例 http://doc.postsharp.net/disposable#customize。最后一节展示了一种自定义处置逻辑的方法(来自以下示例的代码),但它无法编译(假设 Formatter 为 System.Runtime.Serialization.Formatter)。调用 base.Dispose 导致编译器错误 'object' 不包含 'Dispose' 的定义。我读错了这个例子吗?自定义dispose方法有什么方法?

[Disposable]
public class MessageFormatter : Formatter
{

  [Child]
  MessageSink sink;

  public bool IsDisposed { get; private set; }

  protected virtual void Dispose( bool disposing )
  {
    base.Dispose( disposing );

    this.IsDisposed = true;
  }
}

对于未自定义处置逻辑的 类(下面示例中的更多代码),无法调用 Dispose 方法(HomeMadeLogger.Dispose 不存在)。

[Disposable]
public class HomeMadeLogger
{
    [Child]
    public AdvisableCollection<Context> LoggingContexts { get; set; }
}

我找到了这篇简要讨论 Disposable 属性的文章:http://www.codeproject.com/Articles/774482/PostSharpin-Part。它指出

... to use your parent type in a using statement you must initialize it outside the scope of the using to avoid the build-time error type used in a using statement must be implicitly convertible to System.IDisposable

var order = new Order { Id = 1, OrderDate = DateTime.Now };
using (order as IDisposable)
{
   ...
}

这种使用方法效果很好。有没有办法显式处理?

文档页面不正确(我为此提交了一个内部错误)。如果你声明了一个虚方法,你不应该调用 base.Dispose,只有当你重写基 class.

中的相同虚方法时

要调用 public Dispose 方法,请使用 ((IDisposable)order).Dispose()Post.Cast<Order,IDisposable>(order).Dispose()。第二个构造看起来很奇怪,但它在构建时得到了验证。