gpt4 book ai didi

c# - 如何在我的自定义类上使用 IDisposable?

转载 作者:太空宇宙 更新时间:2023-11-03 17:12:53 24 4
gpt4 key购买 nike

这是我的:

public void FindByID(string id)
{
using (Parser parser = new Parser()) {
if ( parser.LoadUserById(id)) {
ID = parser.FindID();
Name = parser.FindName();
// ...
}
else {
MessageBox.Show("User not found.");
}
} // end using block. parser is disposed so its memory is free to use again.
}

这是实际的解析器类本身:

public class Parser : IDisposable
{
XDocument doc;
bool userExists = true;
private const string xmlInformationAddress =
"http://www.dreamincode.net/forums/xml.php?showuser={0}";

public bool LoadUserById(string userID)
{
try
{
doc = XDocument.Load(String.Format(xmlInformationAddress, userID));

if (doc.Root.Elements().Any())
{
userExists = true;
return true;
}
else
{
userExists = false;
return false;
}
}
catch (Exception e)
{
doc = new XDocument();
userExists = false;
return false;
}
}
}

它说我没有实现 Dispose() 方法,但我不确定该方法中应该包含什么。

最佳答案

那么,为什么您想要实现IDisposable?如果您没有要处理的东西(这里看起来就是这种情况),那么客户不必调用 Dispose

您似乎认为调用 Dispose 会释放对象占用的内存。这是垃圾收集器的工作 - Dipose 是完全独立的。它旨在释放非托管资源,例如文件句柄(包括那些间接持有的资源,例如对 Streams 的引用)。

在这种情况下:

  • 不要实现IDisposable
  • 去掉调用代码中的 using 语句
  • 相信 GC :)

关于c# - 如何在我的自定义类上使用 IDisposable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3188788/

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