如何以其他方法正确放置本地创建的对象?

问题描述 投票:0回答:1

所以我有一个实现IDisposable的类,并且我有几个方法(在另一个类中),它们遵循下面的模式:

public void SomeMethod()
{
    DisposableObject disposableObject = new DisposableObject();

    // Do some stuff with the object

    SomeOtherMethod(disposableObject);
    disposableObject.Dispose();
}

虽然所有这些方法都做不同的事情,但它们都在最后调用SomeOtherMethod,这在不再需要可抛弃对象之前会做一些其他事情。当我将disposableObject.Dispose();移到SomeOtherMethod时,Visual Studio给我一条消息,说:“ 使用推荐的处置模式以确保将由'new DisposableObject()'创建的对象处置在所有路径上:使用语句/声明或try / finally“]

无论是否使用SomeOtherMethod关键字将一次性对象传递到ref,都会出现此消息。

我的问题是,只要SomeOtherMethod对其调用Dispose(),该对象是否会被处置?我假设它会,并且Visual Studio继续发送消息只是因为它不“知道”在后续方法中该对象发生了什么,但是我很乐意对此进行确认!

c# idisposable
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.