使用关键字会导致对象超出范围

本文关键字:对象 范围 关键字 | 更新日期: 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

一些要点(如上面的评论所示):

  1. 这永远不会是真的,因为你有两个不同的实例。除非该类重写了相等运算符

  2. 这是无效的,也不会编译,你不能重新分配using语句中使用的变量

  3. 这里ok将超出范围,它也会在这一点上被释放,假设它实现了 IDisposible - 我认为如果它不实现 IDisposable 它就不会编译

总的来说,你似乎想做的事情根本没有多大意义。