如果有垃圾收集,为什么我应该使用封装对象 [英] Why should I encapsulate objects in using if there is garbage collection

查看:106
本文介绍了如果有垃圾收集,为什么我应该使用封装对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索这个并没有成功。所以希望这里有人能回答我这个问题,因为我不明白这一点。




  • 这只是一种好的做法,



  • 为什么要打扰.NET的垃圾收集器?



    在这个例子中,我将使用超级简单的数据注解验证过滤器。使用来封装我的数据上下文有什么好处?

      public静态ValidationResult ValidateUniqueUsername(字符串用户名,对象上下文)
    {
    using(var db = new MainDataContext())//有什么意义?
    {
    var user = db.Users.SingleOrDefault(x => x.Username == username);

    if(user == null)返回ValidationResult.Success;
    返回新的ValidationResult(用户名已被占用);
    }
    }


    解决方案

    使用子句基本解开这个:

      ISomeDisposable一次性= new SomeDisposable ); 
    尝试
    {
    //您的代码在这里
    }
    终于
    {
    if(一次性!= null)
    一次性.Dispose();





    $ b因此,如你所见,如果你的代码抛出异常,对象被处置。如果不抛出异常,它仍然处置(因此最终使用 块)。它确保你的对象被处置


    I was searching this on the internet and with no success. So hopefully someone here can answer me this because I don't understand the point of it.

    • Is it just good practice or it actually does something?
    • Why should I bother if .NET has very good garbage collector?

    Example

    In this example I will use super-simple data-annotation validation filter. What is the benefit of encapsulating my data context in using?

    public static ValidationResult ValidateUniqueUsername(string username, object context)
    {
        using (var db = new MainDataContext()) // What's the point?
        {
            var user = db.Users.SingleOrDefault(x => x.Username == username);
    
            if (user == null) return ValidationResult.Success;
            return new ValidationResult("Username already taken");
        }
    }
    

    解决方案

    The using clause basically unwraps to this:

    ISomeDisposable disposable = new SomeDisposable();
    try
    {
        // your code here
    }
    finally
    {
        if(disposable != null)
            disposable.Dispose();
    }
    

    So, as you can see, if your code throws an exception, the disposable object is Disposed. If you don't thrown an exception, it is still disposed (hence the use of the finally block). It ensures your object is disposed.

    这篇关于如果有垃圾收集,为什么我应该使用封装对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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