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

在C#中使用块的别名

发布时间:2020-12-15 23:49:39 所属栏目:百科 来源:网络整理
导读:我对以下代码有疑问: DisposableObject holdon = null;using (DisposableObject o = new DisposableObject()){ Console.WriteLine("Inside using block"); holdon = o;}holdon.Method(); 当我运行这段代码时,我希望在holdon.Method()行上得到一个异常,但令
我对以下代码有疑问:

DisposableObject holdon = null;

using (DisposableObject o = new DisposableObject())
{
    Console.WriteLine("Inside using block");
    holdon = o;
}

holdon.Method();

当我运行这段代码时,我希望在holdon.Method()行上得到一个异常,但令我惊讶的是,它很高兴地调用了Method()而没有任何问题.我能够确认在点击使用块的末尾时正在调用DisposableObject.Dispose().这提出了一个问题,我没有很多运气在MSDN上找到答案.在使用块之后,尽管调用了Dispose(),holdon仍然指向内存中的有效对象.那么holdon仍然指向o先前指向的同一个对象,还是指向o的副本?

解决方法

处置对象与从内存中删除对象无关.它只意味着在该对象上调用Dispose()方法.所有进一步的操作都取决于您已处置的对象的IDisposable实现.在某些情况下,对象设置为“已处置”状态,所有进一步的操作都会引发异常(ObjectDisposedException).但是,当您实现IDisposable时,您可以自由地做任何事情(或不做).

例如.这是一个完全有效的IDisposable实现(fiddle):

public class CrazyDisposable : IDisposable
{
    public int Counter { get; private set; }
    public void Dispose() => Counter++;
}

进一步阅读:using statement (C# Reference).

特别是解释为什么最好将一次性对象的范围限制为使用块的部分:

You can instantiate the resource object and then pass the variable to
the using statement,but this is not a best practice. In this case,
the object remains in scope after control leaves the using block even
though it will probably no longer have access to its unmanaged
resources. In other words,it will no longer be fully initialized. If
you try to use the object outside the using block,you risk causing an
exception to be thrown
. For this reason,it is generally better to
instantiate the object in the using statement and limit its scope to
the using block.

正如您所看到的那样 – 它是允许的,但是当您访问已处置的对象时存在风险.

(编辑:李大同)

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

    推荐文章
      热点阅读