when you use using(...), the system calls the Dispose method on the object, so you'd better not return the object like you are doing

解决方案 »

  1.   

    using(AA a=..)
    {
      return a;
    }
    块退出后,(a as IDisposable).Dispose 会无条件执行(即使是有异常抛出)
    当然,此时a并没有被回收.
    由于有return的引用,a能被正确地返回。
    可是返回的是一个已经废弃的对象。
    使用该对象已经没有意义,或者会抛出异常。
      

  2.   

    to.lostinet,saucer  
    以上的朋友注意了,我贴的这段代码是来自例子的,难道说错了。我没有打错代码,请大家研究一下,难道真的错了,return 来的东西当然要拿来用的。
      如果拿来用的,肯定不能释放,就算不会立即释放,这样也不稳定安全
      

  3.   

    from
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_8_13.asp.....using (R r1 = new R()) {
       r1.F();
    }is precisely equivalent toR r1 = new R();
    try {
       r1.F();
    }
    finally {
       if (r1 != null) ((IDisposable)r1).Dispose();
    }
    so roles.Dispose() is called before your GetRoleList() returns to the caller>>>>我贴的这段代码是来自例子的
    where is the 例子? any URL?
      

  4.   

    saucer(思归) :我认为更确实的是:R r1 = new R();
    R rxxxxx1=r1;
    try {
       r1.F();
    }
    catch(Exception x)
    {
        throw(x);
    }
    finally {
       ((IDisposable)rxxxxx1).Dispose();
    }
      

  5.   

    或者这样?R r1 = new R();
    IDisposable tempVar001=r1;
    try {
       r1.F();
    }
    catch(Exception x)
    {
        throw(x);
    }
    finally {
       tempVar001.Dispose();
    }
      

  6.   

    that is the sample code from MSDN, you do not need catch block if you are not going to handle the exception
      

  7.   

    恩。。明白了。。
    不catch的话异常会传递下去吧?
      

  8.   

    不过if (r1 != null) ((IDisposable)r1).Dispose();仍然是不妥的。R r1 = new R();
    IDisposable tempVar001=r1 as IDisposable;
    try {
       r1.F();
    }
    finally {
       tempVar001.Dispose();
    }
      

  9.   

    does IDisposable have F() method? I think you miss the point although 
     if (r1 != null) 
    seems unnecessary, I think the following is better:R r1 = null;
    try 
    {
       r1 = new R();
       r1.F();
    }
    finally 
    {
       if (r1 != null) ((IDisposable)r1).Dispose();
    }
      

  10.   

    不是吧?
    如果
    R ra=new R();
    using(R r1=new R())
    {
        R r2=r1;
        r1=ra;
        r2.F();
    }

    那么你认为Disposable执行不?执行哪个?当然可能是我理解你的意思错了。有点文字游戏的感觉。。
    反正调用Dispose不是依赖r1所引用的对象而定。。
      

  11.   

    修正:反正调用Dispose不是依赖r1 _后来_ 所引用的对象而定。。
      

  12.   

    对。。~~~你这个也有道理。
    因为R()可能会抛出异常:
    那么
    using(R r1=new R())
    {
    }
    表示为:IDisposable temVar001=null;
    try
    {
        R r1=new R();
        temVar001=r1 as IDisposable;
    }
    finally
    {
        if(temVar001!=null)temVar001.Dispose();
    }你认为如何?
      

  13.   

    按照你们的意思,我的例子出错了,是吗?给一个严肃肯定的答复
    我会给你们俩添分的,今天我心情不错,刚装了vs.net正式版,发觉速度快很多,呵呵。