为什么我在 C# 中使用 Dispose() 时出错

Why I am getting error when using Dispose() in C#

我正在尝试处理 c# 中的对象。但是当我使用 Dispose() 方法时出现错误。我在下面提到了我尝试过的代码。

尝试过的代码:

public class ParentModel : ParentModelBase, IDisposable
  {

     protected override void OnDispose()
        {
            createdObject.PageMaximizedViewModel = null;
            createdObject = null;
            createdObject.Dispose();
            base.OnDispose();
        }
  }

错误:

‘ParentCreatedClass’ does not contain a definition for ‘Dispose’ and no accessible extension method ’Dispose’ accepting a first argument of type ‘ParentCreatedClass’ could be found(are you missing a using directive or an assembly reference?) Can not resolve symbol ‘Dispose’

我正在为这些时间而苦苦挣扎。我该如何解决这个问题?

ParentCreatedClass 根本没有 public Dispose() 方法 - 你不能调用不存在的方法....

显然,ParentCreatedClass 要么没有实现 IDisposable 接口,要么显式实现了它,这意味着您必须先将其转换为 IDisposable,然后才能调用 Dispose() 就可以了 - 所以试试这个:

protected override void OnDispose()
{
    createdObject.PageMaximizedViewModel = null;
    ((IDisposable)createdObject).Dispose(); 
    base.OnDispose();
}

Here's an online demo.

此外,即使此代码已编译,您在将 null 分配给引用后调用 .Dispose()(或与此相关的任何其他方法)将导致 NullReferenceException - 从您的代码中删除 createdObject = null; 行。没用。

ParentCreatedClass 应该实施 IDisposable 以便您能够调用 createdObject.Dispose();

请参阅此 link 以了解如何正确实施它。

同样 ParentModel class 应该按照 link.

中的描述正确实施 IDisposable

ParentModel 应该有一个 public void Dispose(){..} 方法,如 IDisposable 接口中定义的那样。