使用关键字会导致对象超出范围
本文关键字:对象 范围 关键字 | 更新日期: 2023-09-27 18:32:04
为什么在 if 语句中使用对象时ok
超出范围? 以及如何处置对象ok
?
public class hello : IDisposable {
}
public class hi{
private void b()
{
using(hello ok = new hello());
hello no = new hello();
if( ok == no )
{
ok = no;
}
}
}
您没有正确使用 using
语句,您想要的如下:
using(hello ok = new hello())
{
hello no = new hello();
if( ok == no )//Point 1
{
ok = no;//Point 2
}
}//Point 3
一些要点(如上面的评论所示):
这永远不会是真的,因为你有两个不同的实例。除非该类重写了相等运算符
这是无效的,也不会编译,你不能重新分配
using
语句中使用的变量这里
ok
将超出范围,它也会在这一点上被释放,假设它实现了 IDisposible - 我认为如果它不实现 IDisposable 它就不会编译
总的来说,你似乎想做的事情根本没有多大意义。