gpt4 book ai didi

c# - 如果我在使用语句结束之前调用 Dispose() 会发生什么?

转载 作者:太空狗 更新时间:2023-10-29 18:16:12 25 4
gpt4 key购买 nike

我有这段代码,我担心它“不安全”我在 using 语句结束之前使用了 Dispose() ,对我来说这有点不合逻辑,但它工作得很好。那么,它安全吗?

using (FileStream stream = new FileStream(SfilePath, FileMode.Open))
{
try
{
XmlSerializer deserializer = new XmlSerializer(typeof(HighscoresViewModel));
HVM = deserializer.Deserialize(stream) as HighscoresViewModel;
}
catch (InvalidOperationException)
{
stream.Dispose();
(new FileInfo(SfilePath)).Delete();
HVM = new HighscoresViewModel();
}
}

最佳答案

IDisposable.Dispose 的文档状态:

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

假设 IDisposable 被正确实现,这种使用是安全的。 Dispose 将被第二次调用,第二次什么都不做。

关于c# - 如果我在使用语句结束之前调用 Dispose() 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18175368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com