简体   繁体   English

在控制器内部使用指令

[英]Using directives inside controller

How can I avoid repeating 10+ using directives inside all of my controllers? 如何避免在所有控制器中使用指令重复10+?

There are about 10+ more using directives in each controller because they reference core framework features that we use in our company. 每个控制器中大约有十多个使用指令,因为它们引用了我们公司使用的核心框架功能。 I know you're going to say that logic should be split up so I don't need them all any longer, but that's not an option. 我知道您会说逻辑应该分开,这样我就不再需要它们,但这不是一个选择。

So to be clear, I'm talking about this: 因此,我要说的是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using Kendo.Mvc.UI;

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. using语句确保即使在调用对象的方法时发生异常,也将调用Dispose。 You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; 通过将对象放在try块中,然后在finally块中调用Dispose,可以达到相同的结果。 in fact, this is how the using statement is translated by the compiler. 实际上,这就是编译器翻译using语句的方式。

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

Translated by compiler 由编译器翻译

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

So in your case you can add add object initialization in single block and dispose all in the finally block, see below example, 因此,在您的情况下,您可以在单个代码块中添加添加对象初始化,然后将其全部放置在finally代码块中,请参见以下示例,

{
  Font font1 = new Font("Arial", 10.0f);
 Font font2 = new Font("Arial", 10.0f);
 Font font3 = new Font("Arial", 10.0f);
 Font font4 = new Font("Arial", 10.0f);
 Font font5 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet; 
  }
  finally
  {

      ((IDisposable)font1).Dispose();

      ((IDisposable)font2).Dispose();

      ((IDisposable)font3).Dispose();

      ((IDisposable)font4).Dispose();

      ((IDisposable)font5).Dispose();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM