-2

为什么ok在 if 语句中使用对象时超出范围?以及如何处理对象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;
        }
    }
}
4

1 回答 1

2

您没有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 它将无法编译

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

于 2013-09-20T12:49:19.577 回答