加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么处理对象不会抛出异常使用它?

发布时间:2020-12-15 06:31:59 所属栏目:百科 来源:网络整理
导读:在被处置对象上调用方法是合法的吗?如果是,为什么? 在以下演示程序中,我有一个一次性类A(它实现了IDisposable接口).据我所知,如果我将一次性对象传递给using()构造,那么Dispose()方法会在结束括号中自动调用: A a = new A();using (a){ //...}//---------
在被处置对象上调用方法是合法的吗?如果是,为什么?

在以下演示程序中,我有一个一次性类A(它实现了IDisposable接口).据我所知,如果我将一次性对象传递给using()构造,那么Dispose()方法会在结束括号中自动调用:

A a = new A();
using (a)
{
   //...
}//<--------- a.Dispose() gets called here!

//here the object is supposed to be disposed,//and shouldn't be used,as far as I understand.

如果是正确的,那么请解释这个程序的输出:

public class A : IDisposable
{
   int i = 100;
   public void Dispose()
   {
      Console.WriteLine("Dispose() called");
   }
   public void f()
   {
      Console.WriteLine("{0}",i); i  *= 2;
   }
}

public class Test
{
        public static void Main()
        {
                A a = new A();
                Console.WriteLine("Before using()");
                a.f();
                using ( a) 
                {
                    Console.WriteLine("Inside using()");
                    a.f();
                }
                Console.WriteLine("After using()");
                a.f();
        }
}

输出(ideone):

Before using()
100
Inside using()
200
Dispose() called
After using()
400

如何在被处理对象上调用f()?这是允许的吗?是的,那为什么?如果没有,那为什么上面的程序在运行时没有异常?

我知道使用使用的流行结构是这样的:

using (A a = new A())
{
   //working with a
}

但我只是在试验,所以我写的不同.

解决方法

处置并不意味着消失.处理仅意味着任何非托管资源(如文件,任何类型的连接…)已被释放.虽然这通常意味着该对象不提供任何有用的功能,但是仍然可能存在不依赖于该非托管资源的方法,并且照常工作.

处理机制存在.net(并继承,C#.net)是一个垃圾回收的环境,这意味着你不负责内存管理.但是,垃圾收集器无法决定是否使用非托管资源,因此您需要自己做.

如果您想要方法在对象抛出后抛出异常,则需要一个布尔值来捕获处理状态,一旦对象被处理,您将抛出异常:

public class A : IDisposable
{
   int i = 100;
   bool disposed = false;
   public void Dispose()
   {
      disposed = true;
      Console.WriteLine("Dispose() called");
   }
   public void f()
   {
      if(disposed)
        throw new ObjectDisposedException();

      Console.WriteLine("{0}",i); i  *= 2;
   }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读