如何创建对象以提高内存和性能?

时间:2019-06-13 13:01:26

标签: c# constructor dependencies idisposable solid-principles

我应该如何处理对象创建过程,因为垃圾收集器不会清理C#中的非托管资源?

1)我通常这样做。 2)然后我想出了以下方法:

1)

public class GeneralPageController : Controller
{
    GeneralPageService generalPageService = new GeneralPageService();
    GeneralPageCategoryService categoryService = new 
        GeneralPageCategoryService();
    MultiMediaCategoryService multiMediaCategoryService = new 
        MultiMediaCategoryService();
}

2)

public class GeneralPageController : Controller
{
    protected GeneralPageService _generalPageService;
    protected GeneralPageCategoryService _categoryService;
    protected MultiMediaCategoryService _multiMediaCategoryService;

    public GeneralPageController()
    {
        _generalPageService = new GeneralPageService();
        _categoryService = new GeneralPageCategoryService();
        _multiMediaCategoryService = new MultiMediaCategoryService();
    }
    public new void Dispose()
    {
        _generalPageService.Dispose();
        _categoryService.Dispose();
        _multiMediaCategoryService.Dispose();
    }
}

0 个答案:

没有答案