【问题标题】:Cancel the Initialization of a UserControl or Dispose it in the constructor取消 UserControl 的初始化或在构造函数中将其 Dispose
【发布时间】:2015-07-27 05:31:08
【问题描述】:

我正在 WPF 应用程序中创建一个 UserControl 对话框。 这是它的构造函数:

public ExcelExportView()
{
  InitializeComponent();

  // some stuffs here.
  // IsCancelled may got the value true/false

  if (IsCancelled)
  {
    // is there anyway to dispose the UserControl here?
  }
}

这里我使用Caliburn.Micro 来引导我的应用并创建视图。

所以问题是:有没有办法在构造过程中处理 UserControl?

【问题讨论】:

    标签: c# wpf constructor user-controls caliburn.micro


    【解决方案1】:

    Dispose 方法只是另一种方法。您可以随时随地调用它。事实上,在让它们超出范围之前,您应该为任何可用的一次性实例调用它。

    这取决于你想在构造函数的这个阶段处理什么。如果您初始化了任何 Disposable 对象,则可以 Dispose 它们。首先检查它们是否不为空..

    话虽如此,这个代码/设计对我来说并不好闻。

    编辑

    默认情况下,UserControl 不是 Disposable 的,因为没有任何可丢弃的对象。当你有一个包装非托管资源的类或当你的类有一个实现 IDisposable 的字段时,实现 IDisposable。

    【讨论】:

    • 如何调用该方法?这里没有Dispose()
    • @Envil:当然,因为您还没有在 UserControl 中实现 IDisposable。 UserControl 默认不是 Disposable 的,因为没有任何可丢弃的对象。查看“何时实施 IDisposable”stackoverflow.com/questions/1125693/…
    • 谢谢,我学到了一些东西。但实际上,在实现了 IDisposable 接口之后,Dialog 仍然出现了。我发现了我的设计缺陷,所以我不需要像那样调用 Dispose。再次感谢您的帮助。
    • @Envil:很高兴您了解了 IDisposable。如果您没有任何 Disposable 对象、事件订阅或非托管资源,则无需 Dispose。
    猜你喜欢
    • 2012-07-11
    • 2015-08-28
    • 2012-03-05
    • 2018-07-27
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多