C#:使用块:对象重新初始化 [英] C#: using block: object re-initialization

查看:389
本文介绍了C#:使用块:对象重新初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何时候都避免使用块是一个坏主意,在重新初始化。我仍然要问这样的:



为什么使用调用Dispose原始值,而不是在最后引用或重新初始化(如果尝试终于恰好块使用)

  MyClass的b =新MyClass的(); //实现IDisposable 
MyClass的C =新MyClass的( );
MYCLASS一个;

使用(A =新MyClass的())
{
A = B;
A = C;
}

在上面的代码中处置将被要求原始参考,而不是新的参考。这可以通过打印在Dispose方法控制台的东西很容易地验证。



然而,随着尝试{} finally代码的最后一个引用的Dispose方法被调用。

 
{
A =新MyClass的();
A = B;
A = C;
}
终于
{
a.Dispose();
}

MSDN 的:using语句确保了被废弃,即使当你在调用对象的方法发生异常叫做

 使用(字体font1 =新的字体(宋体,10.0f))
{
字节字符集= font1.GdiCharSet;
}



基本上是使用可转换为:

  {
字体font1 =新的字体(宋体,10.0f);

{
字节字符集= font1.GdiCharSet;
}
终于
{
如果
((IDisposable接口)font1).Dispose()(font1!= NULL);
}
}


解决方案

的编译器生成代码:

  MyClass的b =新MyClass的(); 
MYCLASS一个;
MyClass的CS $ 3 $ 000 = A =新MyClass的();
尝试{
A = B;
}
终于{
如果(CS $ 3 $ 000 =空!)CS $ 3 $ 000.Dispose();
}



自动生成的CS $ 3 $ 1000名本地变量实现合同。


Re-initialization within "using" block is a bad idea, to be avoided at all times. Still i am going to ask this:

Why does "using" call dispose on the original value and not on the last reference or re-initialization (which happens if try finally block is used)

MyClass b = new MyClass();// implements Idisposable
MyClass c = new MyClass();
MyClass a ; 

 using (a = new MyClass())
 {
                a = b;
                a = c;
 }

In the above code dispose will be called on original reference and not the newer referenced. This can be easily verified by printing something on console in the dispose method.

However with try{} finally code the last reference dispose method is called.

try
{
   a = new MyClass();
   a = b;
   a = c;
 }
  finally 
   {
   a.Dispose();
  }

MSDN : The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

Basically "using" translates to:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

解决方案

The compiler generates this code:

MyClass b = new MyClass();
MyClass a;
MyClass cs$3$000 = a = new MyClass();
try {
  a = b;
}
finally {
  if (cs$3$000 != null) cs$3$000.Dispose();
}

The auto-generated cs$3$000 local variable implements the contract.

这篇关于C#:使用块:对象重新初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆